What is the best way to filter a Java Collection?

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

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

27条回答
  •  一向
    一向 (楼主)
    2020-11-21 07:37

    With Guava:

    Collection collection = Lists.newArrayList(1, 2, 3, 4, 5);
    
    Iterators.removeIf(collection.iterator(), new Predicate() {
        @Override
        public boolean apply(Integer i) {
            return i % 2 == 0;
        }
    });
    
    System.out.println(collection); // Prints 1, 3, 5
    

提交回复
热议问题