Collect stream with grouping, counting and filtering operations

后端 未结 3 1516
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    I personally prefer Holger's solution (+1), but, instead of removing elements from the groupingBy map, I would filter its entrySet and map the result to a Set in the finalizer (it feels even more streamy to me)

        Set commonlyUsed = allWords.stream().collect(
                collectingAndThen(
                    groupingBy(identity(), counting()), 
                    (map) -> map.entrySet().stream().
                                filter(e -> e.getValue() > 2).
                                map(e -> e.getKey()).
                                collect(Collectors.toSet())));
    

提交回复
热议问题