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
Difference between 2 collections? (elements in collection1, but not in collection2)
提问by stefan.at.wpf
In Java (maybe using Guava?), is there some method provided to get the difference of two Collection
s, e.g. a List
and a Set
withoutmodifying one of these Collection
s (else there would be collection1.removeAll(collection2)
?
在 Java 中(也许使用 Guava?),是否提供了一些方法来获得两个Collection
s的差异,例如 aList
和 aSet
而不修改其中一个Collection
(否则会有collection1.removeAll(collection2)
?
In Guava there is Sets.difference(set1,set2)
, but it only works for Set
s, not for arbitrary collections.
在 Guava 中有Sets.difference(set1,set2)
,但它只适用于Set
s,不适用于任意集合。
Thanks for any hint!
感谢您的任何提示!
回答by Frank Pavageau
You can filter the first Collection
using built-in Predicate
s:
您可以Collection
使用内置Predicate
s过滤第一个:
Collections2.filter(c1, Predicates.not(Predicates.in(c2))
It works with any kind of Collection
s, but obviously it's better if c2
is a Set
.
它适用于任何类型的Collection
s,但显然如果c2
是Set
.
回答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