How to use Collectors.grouping in the Java 8 Stream API to create a map

I am looking for the first time for Stream API Java 8. And I tried to create a filter to remove elements from the map.

This is my map:

Map<String, Integer> m = new HashMap<>(); 

I want to delete entries with a value of <= than 0. Therefore, I want to apply a filter and return a new map (Map <String, Integer>).

This is what I tried:

 m.entrySet().stream().filter( p -> p.getValue() > 0).collect(Collectors.groupingBy(s -> s.getKey())); 

I get HashMap <String, ArrayList <HashMap $ Node β†’. So, not what I was looking for.

I also tried:

 m.entrySet().stream().filter( p -> p.getValue() > 0).collect(Collectors.groupingBy(Map::Entry::getKey, Map::Entry::getValue)); 

And this causes:

 // Error:(50, 132) java: method reference not expected here 

Basically, I don’t know how to build the values ​​of my new Map.

This is javadoc of Collectors , they wrote some groupingBy examples, but I couldn’t get it working.

So, how do I write to collect so that my Map is built the way I want?

+7
java java-stream
source share
1 answer

You do not need to group the flow elements again, they are already "displayed" - you just need to assemble them:

 m.entrySet().stream() .filter(p -> p.getValue() > 0) .collect(toMap(Entry::getKey, Entry::getValue)); 

Import

 import java.util.Map.Entry; import static java.util.stream.Collectors.toMap; 
+11
source share

All Articles