The difference between the two collections? (items in collection1 but not in collection2)

In Java (possibly using Guava?) Is there any method to get the difference between two Collection s, for example. a List and a Set without changing one of these Collection (otherwise would it be collection1.removeAll(collection2) ?

Guava has Sets.difference(set1,set2) , but it only works for Set s, and not for arbitrary collections.

Thanks for any hint!

+7
source share
2 answers

You can filter the first Collection using the built-in Predicate s:

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

It works with any type of Collection s, but it is obviously better if c2 is Set .

+13
source

ApacheCommons CollectionUtils has a disjuction method which

Returns a collection containing an exceptional disjunction (symmetric difference) of Iterables data

+3
source

All Articles