0

I am receiving a rest response in following format.

{
    "query_result": {
        "status": "SUCCESS",
        "message": "Results Found",
        "results": [
            {
                "key": "123"
            },
            {
                "key": "465"
            }
        ]
    }
}

From this response, I want to create a list of String from the keys. Thus looking to get a list outcome as follows:

["123", "456"]

Trying to produce the output as follows but stuck at the map step in following code block.

public Optional<List<String>> get(HttpEntity<Request> request){
    ResponseEntity<Response> response = getResponse(request); // this response holds above json data 

    return Optional.ofNullable(response)
            .map(ResponseEntity::getBody)
            .map(Response::getQueryResult)
            .map(QueryResult::getResults)
            .filter(CollectionUtils::isNotEmpty)
            .map(results -> results.) // Stuck here. results here is the list of results shown in above json. 
}

I am not able to pull out all the key's values from here. I end up having to indicate index as follows which is not going to work since I want all keys.

.map(results -> results.get(0))

Tried considering using iterator but that would again only end up capturing the first key only.

.filter(CollectionUtils::isNotEmpty)
.map(List::iterator)
.map(Iterator::next)
.map(result -> result.getKey())

Could I please get some help with this. Thanks.

1 Answer 1

3
.map(QueryResult::getResults)
.filter(CollectionUtils::isNotEmpty)
.map(results -> results.stream().map(Key::getKey).collect(Collectors.toList()));

Assumed that each key object is mapped correctly to a class called Key which looks like this:

class Key {
    String key;

    String getKey() {
        return key;
    }
}

you want on your Optional chain to transform its internal List of Keys to a List of Strings. So the final step just takes care of that part.

Note
  1. Your method returns an Optional list. Generally it's better on semantics if you return an empty list instead of null, but that's up to the implementation.

  2. If it's getting hard to understand the lambdas, move their logic to methods. For instance the above chain can become:

List<String> collectKeys(List<Key> keys) {
    return keys.stream().map(Key::getKey).collect(Collectors.toList())
}

// and then:
.map(QueryResult::getResults)
.filter(CollectionUtils::isNotEmpty)
.map(this::collectKeys);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.