I\'m trying to collect stream throwing away rarely used items like in this example:
import java.util.*;
import java.util.function.Function;
import static java.ut
There is no way around creating a Map
, unless you want accept a very high CPU complexity.
However, you can remove the second collect
operation:
Map map = allWords.stream()
.collect(groupingBy(Function.identity(), HashMap::new, counting()));
map.values().removeIf(l -> l<=2);
Set commonlyUsed=map.keySet();
Note that in Java 8, HashSet
still wraps a HashMap
, so using the keySet()
of a HashMap
, when you want a Set
in the first place, doesn’t waste space given the current implementation.
Of course, you can hide the post-processing in a Collector
if that feels more “streamy”:
Set commonlyUsed = allWords.stream()
.collect(collectingAndThen(
groupingBy(Function.identity(), HashMap::new, counting()),
map-> { map.values().removeIf(l -> l<=2); return map.keySet(); }));