Reputation: 2404
I am looking for the first time to the Stream API of Java 8. And I have tried to create a filter to remove elements from a Map.
This is my Map:
Map<String, Integer> m = new HashMap<>();
I want to remove entries with value <= than 0. So I want to apply a filter and get back a new map(Map<String, Integer>).
This is what I have been trying:
m.entrySet().stream().filter( p -> p.getValue() > 0).collect(Collectors.groupingBy(s -> s.getKey()));
I get a 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 the javadoc of Collectors, they wrote a few examples of groupingBy, but I have not been able to get it working.
So, how should I write the collect to get my Map built as I want?
Upvotes: 7
Views: 5279
Reputation: 328598
You don't need to group the stream items again, they are already "mapped" - you just need to collect them:
m.entrySet().stream()
.filter(p -> p.getValue() > 0)
.collect(toMap(Entry::getKey, Entry::getValue));
imports:
import java.util.Map.Entry;
import static java.util.stream.Collectors.toMap;
Upvotes: 11