使用谓词过滤列表

时间:2014-11-12 13:33:21

标签: java guava predicate

我有两个对象的数组列表,我如何使用guava的过滤器来过滤掉每个对象的标题彼此相等?每个对象都有一个getTitle()方法。

List<Foo> listA;
List<Bar> listB;
for (Foo item: listA)
{
   Iterables.filter(listB, new Predicate()
   {
     //predicate here
   }
}

1 个答案:

答案 0 :(得分:0)

使用guava可以像这样完成(不检查null,并优化空集合):

// If any of the arrays empty or null, you can return straight away
Set<String> titlesB = new HashSet<String>(Collections2.transform(listB, (b) -> b.getTitle()));
Set<String> titlesA = new HashSet<String>(Collections2.transform(listA, (a) -> a.getTitle()));

// You can further optimize checking the smallest collection (contains is O(1) operation on Set)
Set<String> titlesIntersection = Collections2.filter(titlesB, (b) -> titlesA.contains(b));

List<Foo> commonA = Collections2.filter(listA, (a) -> titlesIntersection.contains(a.getTitle()));
List<Foo> commonB = Collections2.filter(listB, (b) -> titlesIntersection.contains(b.getTitle()));

还有,apache commons交叉功能

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/CollectionUtils.html

但无论如何你还需要在那里使用一些额外的步骤。