Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 225
Raul Guiu Avatar asked Mar 26 '14 18:03

Raul Guiu


1 Answers

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;
like image 106
assylias Avatar answered Nov 09 '22 08:11

assylias