如何:在 Java 中查找两个集合之间的集合差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25615974/
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-11-02 08:20:36  来源:igfitidea点击:

How to: Find the Set Difference Between Two Collections in Java

java

提问by leozilla

I am relativly new to Java and I am wondering if there is a method like LINQs "Except" in C# to get the different items of two sets.

我对 Java 比较陌生,我想知道C# 中是否有像 LINQ“ Except”这样的方法来获取两个集合的不同项目。

I looked at CollectionUtilsfrom apache common, Collectionsand Collections2from guava but found no such method.

CollectionUtils从 apache commonCollectionsCollections2guava 中查看,但没有发现这样的方法。

Btw: I am using Java 7 not Java 8.

顺便说一句:我使用的是 Java 7 而不是 Java 8。

回答by Peter Lamberg

I have used Guava Sets.difference.

我用过番石榴Sets.difference

The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).

参数是集合而不是一般集合,但是从任何集合(具有唯一项)创建集合的便捷方法是 Guava ImmutableSet.copyOf(Iterable)。

回答by JosEduSol

Suppose you have:

假设你有:

...
Set<int> s1 = new HashSet<Integer>();
Set<int> s2 = new HashSet<Integer>();
...

You can try this

你可以试试这个

s2.removeAll(s1);

See the doc for Set#removeAll

请参阅Set#removeAll的文档

NOTE: This will modify the set, but you can have a copy of it.

注意:这将修改集合,但您可以拥有它的副本。

回答by Diptesh

You can Try this

你可以试试这个

collection2.removeAll(collection1);

Although this will mutate collection2, so create a copy if you need to preserve it.

虽然这会发生变异collection2,但如果您需要保留它,请创建一个副本。