java 如何将多个集合相交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4009205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:20:58  来源:igfitidea点击:

How to intersect multiple sets?

javasetintersection

提问by vale4674

I have this list:

我有这个清单:

private List<Set<Address>> scanList;

So my list contains multiple scans as you can see. After each scan I add new set into the list.

如您所见,我的列表包含多个扫描。每次扫描后,我将新集合添加到列表中。

After all scans are finished I would like to take only the addresses that occur in every set and put it into:

完成所有扫描后,我只想将每组中出现的地址放入:

private List<Address> addresses;

Does something like this already exists in Set/TreeSet/HashSet?

Set/TreeSet/HashSet 中是否已经存在类似的东西?

EDIT: after answers, retainAll() is the right method. Thank you. Here is the source:

编辑:回答后,retainAll() 是正确的方法。谢谢你。这是来源:

Set<Address> addressCross = scanList.get(0);
for (int i = 1; i < scanList.size(); i++) {
    addressCross.retainAll(scanList.get(i));
}   
for (Address address : addressCross) {
    addresses.add(address);
}

采纳答案by Lavir the Whiolet

See "retainAll()".

请参阅“retainAll()”。

回答by Hyman

you can use retainAll(Collection<?> c), check it out here

你可以使用retainAll(Collection<?> c)在这里查看

A side note: that operation is called intersection.

旁注:该操作称为交集

To convert then it to a Listyou can use the method addAll(Collection<? extends E> c)which should work between all kinds of containers.

要将其转换为 aList您可以使用addAll(Collection<? extends E> c)应该在各种容器之间工作的方法。

eg:

例如:

ArrayList<Address> list = new ArrayList<Address>();
list.addAll(yourSet);

回答by ColinD

With Guava, you could do it like this:

使用Guava,你可以这样做:

Set<Address> intersection = scanList.get(0);
for (Set<Address> scan : scanList.subList(1, scanList.size())) {
  intersection = Sets.intersection(intersection, scan);
}
List<Address> addresses = Lists.newArrayList(intersection);

This creates a view of the intersection of all the sets in the scanListand then copies the addresses in the intersection into a List. You would need to ensure your scanListhas at least one element in it, of course.

这将创建 中所有集合的交集的视图,然后将交集中scanList的地址复制到List. 当然,您需要确保scanList其中至少包含一个元素。