Java streams – how to use conditions on keys to translate all values in a collection map
•
Java
I have a map Let's talk
Map<Long,List<MyObj>>
I want to create a long array in all myobjs, where the key (long) is found in another set ()
anotherSet.contains(long)
Use Java streams
I tried
map.entrySet() .stream() .filter(e->anotherSet(e.getKey())) .flatMap(e.getValue) .collect(Collectors.toList);
But it didn't even compile
Solution
You have some grammatical mistakes
This should produce the list you want:
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 generate 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码