What is the best way to filter a Java Collection?

后端 未结 27 3393
故里飘歌
故里飘歌 2020-11-21 06:55

I want to filter a java.util.Collection based on a predicate.

27条回答
  •  误落风尘
    2020-11-21 07:23

    Since java 9 Collectors.filtering is enabled:

    public static 
        Collector filtering(Predicate predicate,
                                     Collector downstream)
    

    Thus filtering should be:

    collection.stream().collect(Collectors.filtering(predicate, collector))
    

    Example:

    List oddNumbers = List.of(1, 19, 15, 10, -10).stream()
                .collect(Collectors.filtering(i -> i % 2 == 1, Collectors.toList()));
    

提交回复
热议问题