Google Collections独特谓词 [英] Google Collections Distinct Predicate
问题描述
一个人如何实现与Google Collections Collections2.filter方法一起使用的谓词?
How would 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:
创建这样的谓词将需要维护某种状态(即:维护已经看到的一组事物).在Javadoc中明确建议不要这样做.
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);
如果<T>
上的equals()和hashCode()方法未按所需方式定义唯一性,则应编写一个对Collection<T>
和Function<T, Object>
进行操作的实用程序方法,该方法将返回项目类型T
的类型,在使用Function
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
这篇关于Google Collections独特谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!