Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Collections, e.g. a List and a Set without modifying one of these Collections (else there would be collection1.removeAll(collection2)?

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

Thanks for any hint!

like image 300
stefan.at.wpf Avatar asked Apr 10 '13 12:04

stefan.at.wpf


2 Answers

ApacheCommons CollectionUtils has a method named disjuction that

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

like image 51
Mike Avatar answered Oct 22 '22 10:10

Mike


You can filter the first Collection using built-in Predicates:

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

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

like image 37
Frank Pavageau Avatar answered Oct 22 '22 09:10

Frank Pavageau