[英]Difference between 2 collections? (elements in collection1, but not in collection2)
In Java (maybe using Guava?), is there some method provided to get the difference of two Collection
s, eg a List
and a Set
without modifying one of these Collection
s (else there would be collection1.removeAll(collection2)
? 在Java中(可能使用Guava?),是否提供了一些方法来获取两个Collection
的区别,例如List
和Set
而不修改其中一个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! 谢谢你的提示!
You can filter the first Collection
using built-in Predicate
s: 您可以使用内置Predicate
s过滤第一个Collection
:
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
,但显然如果c2
是Set
,它会更好。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.