Java 8流-将方法传递给过滤器 [英] Java 8 streams - passing a method to a filter
本文介绍了Java 8流-将方法传递给过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组整数set2和一个对象:
I have a set of integers set2 and an object:
public class Bucket {
private Integer id;
private Set<Integer> set1;
...
}
我想使用流过滤存储桶,但是仅使用set1与另一个set2相交的存储桶.我尝试了以下代码:
I want to filter Buckets using streams, but only buckets where their set1 has intersection with another set2. I tried the following code:
Set<Bucket> selectedBuckets = allBuckets.stream()
.filter(e -> Sets.intersection(e.getSet1(), set2).size()>1)
.collect(Collectors.toSet());
但是这将返回allBuckets的所有元素,而不是仅返回包含交集的元素.我怎样才能做到这一点 ?
But this would return all elements of allBuckets, instead of only the elements whose sets contains the intersection. How can I do this ?
推荐答案
假设与List
中的任何Bucket
交叉(Set
set1内容)是您要寻找的内容:
What you might just be looking for assuming you meant intersection(of Set
set1 content) with any other Bucket
in the List
:
List<Bucket> allBuckets = new ArrayList<>(); // as you may initialise
Set<Bucket> selectedBuckets = allBuckets.stream()
.filter(e -> allBuckets.stream()
.filter(f -> f != e)
.flatMap(b -> b.getSet1().stream())
.anyMatch(s -> e.getSet1().contains(s)))
.collect(Collectors.toSet());
这篇关于Java 8流-将方法传递给过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文