Google Collections Distinct Predicate
How wou开发者_StackOverflowld one implement a distinct predicate for use with the Google Collections Collections2.filter method?
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
My solution:
// 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();
精彩评论