我想根据谓词筛选java.util.Collection。


当前回答

谷歌的Guava库中的Collections2.filter(Collection,Predicate)方法正是您所寻找的。

其他回答

JFilter http://code.google.com/p/jfilter/最适合您的需求。

JFilter是一个简单、高性能的开源库,用于查询Java bean集合。

关键特性

Support of collection (java.util.Collection, java.util.Map and Array) properties. Support of collection inside collection of any depth. Support of inner queries. Support of parameterized queries. Can filter 1 million records in few 100 ms. Filter ( query) is given in simple json format, it is like Mangodb queries. Following are some examples. { "id":{"$le":"10"} where object id property is less than equals to 10. { "id": {"$in":["0", "100"]}} where object id property is 0 or 100. {"lineItems":{"lineAmount":"1"}} where lineItems collection property of parameterized type has lineAmount equals to 1. { "$and":[{"id": "0"}, {"billingAddress":{"city":"DEL"}}]} where id property is 0 and billingAddress.city property is DEL. {"lineItems":{"taxes":{ "key":{"code":"GST"}, "value":{"$gt": "1.01"}}}} where lineItems collection property of parameterized type which has taxes map type property of parameteriszed type has code equals to GST value greater than 1.01. {'$or':[{'code':'10'},{'skus': {'$and':[{'price':{'$in':['20', '40']}}, {'code':'RedApple'}]}}]} Select all products where product code is 10 or sku price in 20 and 40 and sku code is "RedApple".

java8之前的简单解决方案:

ArrayList<Item> filtered = new ArrayList<Item>(); 
for (Item item : items) if (condition(item)) filtered.add(item);

不幸的是,这个解决方案不是完全通用的,它输出的是一个列表,而不是给定集合的类型。此外,在我看来,引入库或编写函数来包装这段代码似乎有些过分,除非条件很复杂,但随后可以为该条件编写函数。

这里有一些非常棒的答案。对我来说,我想让事情尽可能简单易懂:

public abstract class AbstractFilter<T> {

    /**
     * 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<T> collection) {
        if (CollectionUtils.isNotEmpty(collection)) {
            Iterator<T> iterator = collection.iterator();
            while (iterator.hasNext()) {
                if (excludeItem(iterator.next())) {
                    iterator.remove();
                }
            }
        }
    }
}

这一点,再加上缺少真正的闭包,是我对Java最大的不满。 老实说,上面提到的大多数方法都很容易阅读,而且真的很有效;然而,在学习了。net、Erlang等之后……在语言级别集成的列表理解使一切变得更加清晰。如果没有在语言级别上的添加,Java就不能像这个领域的许多其他语言一样干净。

如果性能非常重要,那么可以使用谷歌集合(或者编写自己的简单谓词实用程序)。Lambdaj语法对某些人来说可读性更好,但效率不高。

然后有一个我写的库。我将忽略任何关于其效率的问题(是的,它很糟糕)......是的,我知道它清楚地基于反射,不,我实际上没有使用它,但它确实工作:

LinkedList<Person> list = ......
LinkedList<Person> filtered = 
           Query.from(list).where(Condition.ensure("age", Op.GTE, 21));

OR

LinkedList<Person> list = ....
LinkedList<Person> filtered = Query.from(list).where("x => x.age >= 21");

谷歌的Guava库中的Collections2.filter(Collection,Predicate)方法正是您所寻找的。