What is the best way to filter a Java Collection?

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

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

27条回答
  •  梦如初夏
    2020-11-21 07:33

    Since the early release of Java 8, you could try something like:

    Collection collection = ...;
    Stream stream = collection.stream().filter(...);
    

    For example, if you had a list of integers and you wanted to filter the numbers that are > 10 and then print out those numbers to the console, you could do something like:

    List numbers = Arrays.asList(12, 74, 5, 8, 16);
    numbers.stream().filter(n -> n > 10).forEach(System.out::println);
    

提交回复
热议问题