1

I am parsing the JSON response from server in Java class. We have utility function to covert JSON to List<Map<String, Object>>. Now I want to collect specific key's value from all objects. For example the JSON I receive is person's data like below

[
 {
   name:'abc',
   city: 'Hyd'
 },
 {
   name:'def',
   city:'NYC'
 }
]

I wanted to try Java8 stream API to get this job done, so here is how i wrote

List<Map<String,Object>> answer = parseJSONReponse(response);
List<Object> collect = answer.stream().map(
            m -> m.entrySet().stream()
                             .filter(e-> e.getKey().equals("name"))
                             .map(e -> e.getValue())
                             .collect(Collectors.toList())
    ).flatMap(l->l.stream()).collect(Collectors.toList());

Please let me know if there is better of writing this stream API.

0

2 Answers 2

3

You don't need to collect inside map, then flatMap as you're creating unnecessary intermediate lists. Just use flatMap directly:

List<Object> collect = answer.stream().flatMap(
            m -> m.entrySet().stream()
                             .filter(e-> e.getKey().equals("name"))
                             .map(e -> e.getValue())
    ).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to get list of another types (Long for example), not Object?
0

You may consider using a parallel stream.

Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism. [1]

This can be easily done by exchanging the stream() methods with parallelStream().

[1] Oracle tutorial on stream parallelism.

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.