Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Collections Distinct Predicate

Tags:

java

guava

How would one implement a distinct predicate for use with the Google Collections Collections2.filter method?

like image 889
javacavaj Avatar asked Aug 10 '26 01:08

javacavaj


1 Answers

If I understand you correctly, I'm not sure that Predicate is the right solution here:

Creating a predicate like that would require maintaining some sort of state (ie: maintaining a Set of things it has seen already). This is explicitly advised against in the javadoc.

The usual way to get the distinct items in a collection would be to just add them all to a set. ie:

Set<T> uniqueItems = Sets.newHashSet(collectionWithPotentialDuplicates);

If the equals() and hashCode() methods on <T> don't define uniqueness the way you want, then you should write a utility method that operates on a Collection<T> and a Function<T, Object> which returns the items of type T which are unique after being converted using the Function

like image 89
Michael D Avatar answered Aug 11 '26 15:08

Michael D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!