What is the best way to filter a Java Collection?

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

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

27条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:21

    "Best" way is too wide a request. Is it "shortest"? "Fastest"? "Readable"? Filter in place or into another collection?

    Simplest (but not most readable) way is to iterate it and use Iterator.remove() method:

    Iterator it = col.iterator();
    while( it.hasNext() ) {
      Foo foo = it.next();
      if( !condition(foo) ) it.remove();
    }
    

    Now, to make it more readable, you can wrap it into a utility method. Then invent a IPredicate interface, create an anonymous implementation of that interface and do something like:

    CollectionUtils.filterInPlace(col,
      new IPredicate(){
        public boolean keepIt(Foo foo) {
          return foo.isBar();
        }
      });
    

    where filterInPlace() iterate the collection and calls Predicate.keepIt() to learn if the instance to be kept in the collection.

    I don't really see a justification for bringing in a third-party library just for this task.

提交回复
热议问题