What is the best way to filter a Java Collection?

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

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

27条回答
  •  醉酒成梦
    2020-11-21 07:38

    Some really great great answers here. Me, I'd like to keep thins as simple and readable as possible:

    public abstract class AbstractFilter {
    
        /**
         * Method that returns whether an item is to be included or not.
         * @param item an item from the given collection.
         * @return true if this item is to be included in the collection, false in case it has to be removed.
         */
        protected abstract boolean excludeItem(T item);
    
        public void filter(Collection collection) {
            if (CollectionUtils.isNotEmpty(collection)) {
                Iterator iterator = collection.iterator();
                while (iterator.hasNext()) {
                    if (excludeItem(iterator.next())) {
                        iterator.remove();
                    }
                }
            }
        }
    }
    

提交回复
热议问题