Guava Collections - 按字符串值数组过滤

Guava Collections - filter by array of String values

我有一个事件对象列表。每个对象公开 getId() getter。我需要过滤集合以仅获取具有特定 ID 的项目,我可以这样做:

Lists.newArrayList(Iterables.filter(ret, x->x.getCategoryId().equals(category)));

因此,我得到了新数组,过滤到项目,其中 getCategoryId() 等于我的特定 category

到目前为止还不错。问题:如果我有 String 值数组(所有类别都用作过滤器)而不是单一的特定类别怎么办?这可能如下所示:

Lists.newArrayList(Iterables.filter(ret, x->x.getCategoryId().equals(categories.get(0)) || x.getCategoryId().equals(categories.get(1)) || ......../*To the end of the list*/));

由于我的 categories 列表是动态的,我需要使用动态查询来应用所有 || 条件。最好的方法是什么?我可以以某种方式循环它或提供 array 作为 filter 方法的标准吗?

注意:我在 Android,所以:

那么,你有什么想法吗?

你所要做的就是构建一个番石榴 Predicate,因为你需要快速查找,首先从该数组构建一个 Set 可能会有所回报:

Set<String> set = new HashSet<>(Arrays.asList(values));   

而不是简单地替换谓词:

x -> set.contains(x.getCategoryId())

仅使用 Java 8,您可以执行以下操作:

final Set<String> categories = new HashSet<>(Arrays.asList("category 1", "category 2"));
ret.stream()
   .filter(x -> categories.contains(x.getCategoryId()))
   .collect(Collectors.toList());