Google Collections Distinct Predicate

How to implement a separate predicate for use with the Collections2.filter method of Google?

+3
source share
2 answers

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

Creating such a predicate will require preserving some state (i.e. preserving the set of things that he has already seen). This is explicitly prohibited in javadoc.

The usual way to get individual items in a collection is to simply add them to the set. i.e:

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

If the equals () and hashCode () methods on <T> do not define uniqueness the way you want, then you should write a utility method that works with Collection<T> and Function<T, Object> , which returns elements of type T , which are unique after conversion with Function

+9
source

My decision:

 // Create unique list final Set<String> unique = new HashSet<String>(FluentIterable .from(sourceList) .transform(new Function<T, String>() { @Override public String apply(T input) { // Here we create unique entry return input.toString(); } }).toSet()); // Filter and remove duplicates return FluentIterable .from(prePscRowList) .filter(new Predicate<T>() { @Override public boolean apply(T input) { boolean exist = false; if(unique.contains(input.toString())){ unique.remove(input.toString()); exist = true; } return exist; } }).toList(); 
0
source

All Articles