3

I have a Map. Let's say

Map<Long, List<MyObj>> 

I want to create a long array where of all MyObj where the key (long) is found in another set()

anotherSet.contains(long)

using java stream.

I tried

map.entrySet()
   .stream()
   .filter(e->anotherSet(e.getKey()))
   .flatMap(e.getValue)
   .collect(Collectors.toList);

But it doesnt even compile

1 Answer 1

7

You had a few syntax errors.

This should produce your desired List :

List<MyObj> filteredList = 
    map.entrySet()
       .stream()
       .filter(e->anotherSet.contains(e.getKey())) // you forgot contains
       .flatMap(e-> e.getValue().stream()) // flatMap requires a Function that 
                                           // produces a Stream
       .collect(Collectors.toList()); // you forgot ()

If you want to produce an array instead of a List, use :

MyObj[] filteredArray = 
    map.entrySet()
       .stream()
       .filter(e->anotherSet.contains(e.getKey()))
       .flatMap(e-> e.getValue().stream())
       .toArray(MyObj[]::new);
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.