java 2个集合之间的区别?(集合1中的元素,但不在集合2中)

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

Difference between 2 collections? (elements in collection1, but not in collection2)

javalistcollectionssetguava

提问by stefan.at.wpf

In Java (maybe using Guava?), is there some method provided to get the difference of two Collections, e.g. a Listand a Setwithoutmodifying one of these Collections (else there would be collection1.removeAll(collection2)?

在 Java 中(也许使用 Guava?),是否提供了一些方法来获得两个Collections的差异,例如 aList和 aSet而不修改其中一个Collection(否则会有collection1.removeAll(collection2)?

In Guava there is Sets.difference(set1,set2), but it only works for Sets, not for arbitrary collections.

在 Guava 中有Sets.difference(set1,set2),但它只适用于Sets,不适用于任意集合。

Thanks for any hint!

感谢您的任何提示!

回答by Frank Pavageau

You can filter the first Collectionusing built-in Predicates:

您可以Collection使用内置Predicates过滤第一个:

Collections2.filter(c1, Predicates.not(Predicates.in(c2))

It works with any kind of Collections, but obviously it's better if c2is a Set.

它适用于任何类型的Collections,但显然如果c2Set.

回答by Mike

ApacheCommons CollectionUtils has a method named disjuction that

ApacheCommons CollectionUtils有一个方法叫disjuction

Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Iterables

返回一个包含给定 Iterables 的互斥析取(对称差异)的 Collection