7

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?

4

1 回答 1

11

您不需要再次对流项目进行分组,它们已经“映射” - 您只需要收集它们:

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

进口:

import java.util.Map.Entry;
import static java.util.stream.Collectors.toMap;
于 2014-03-26T18:28:28.280 回答