【问题标题】:Using predicate to filter a list使用谓词过滤列表
【发布时间】:2014-11-12 13:33:21
【问题描述】:

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

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

【问题讨论】:

标签: java guava predicate


【解决方案1】:

使用 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

但无论如何您都需要在此处使用一些额外的步骤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2018-11-11
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    相关资源
    最近更新 更多