Collect stream with grouping, counting and filtering operations

后端 未结 3 1498
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 19:23

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         


        
3条回答
  •  感情败类
    2021-02-13 19:31

    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(); }));
    

提交回复
热议问题