Java - 不同的对象列表 [英] Java - Distinct List of Objects
问题描述
我有一个列表/对象的集合,可能有或没有相同的属性值。什么是最简单的方法来获得具有相等属性的对象的不同列表?一种集合类型最适合此目的吗?例如,在C#中,我可以用LINQ做类似下面的事情。
var recipients =(from recipient in recipientList
选择收件人).Distinct();
我最初的想法是使用lambdaj(链接文本),但它似乎不支持这一点。
.equals ()
方法,你可能必须实现 .equals()
自己)。通常, HashSet
会使用它:它使用 Object.hashCode()
和 Object.equals()
方法来比较对象。这应该是独特的,足够简单的对象。如果没有,你必须相应地实现 T.equals()
和 T.hashCode()
p> 有关帮助实现equals和hashcode的库,请参阅Gaurav Saini的以下注释。
I have a list/collection of objects that may or may not have the same property values. What's the easiest way to get a distinct list of the objects with equal properties? Is one collection type best suited for this purpose? For example, in C# I could do something like the following with LINQ.
var recipients = (from recipient in recipientList
select recipient).Distinct();
My initial thought was to use lambdaj (link text), but it doesn't appear to support this.
Use an implementation of the interface Set<T>
(class T may need a custom .equals()
method, and you may have to implement that .equals()
yourself). Typically a HashSet
does it out of the box : it uses Object.hashCode()
and Object.equals()
method to compare objects. That should be unique enough for simple objects. If not, you'll have to implement T.equals()
and T.hashCode()
accordingly.
See Gaurav Saini's comment below for libraries helping to implement equals and hashcode.
这篇关于Java - 不同的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!