What is the best way to filter a Java Collection?

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

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

27条回答
  •  醉梦人生
    2020-11-21 07:36

    The setup:

    public interface Predicate {
      public boolean filter(T t);
    }
    
    void filterCollection(Collection col, Predicate predicate) {
      for (Iterator i = col.iterator(); i.hasNext();) {
        T obj = i.next();
        if (predicate.filter(obj)) {
          i.remove();
        }
      }
    }
    

    The usage:

    List myList = ...;
    filterCollection(myList, new Predicate() {
      public boolean filter(MyObject obj) {
        return obj.shouldFilter();
      }
    });
    

提交回复
热议问题