Java - 不同的对象列表 [英] Java - Distinct List of Objects

查看:16
本文介绍了Java - 不同的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表/集合,这些对象可能具有也可能不具有相同的属性值.获得具有相同属性的对象的不同列表的最简单方法是什么?一种集合类型最适合此目的吗?例如,在 C# 中,我可以使用 LINQ 执行以下操作.

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();

我最初的想法是使用 lambdaj(链接文本),但它似乎不支持这一点.

My initial thought was to use lambdaj (link text), but it doesn't appear to support this.

推荐答案

使用接口Set的实现(类T可能需要自定义.equals()code> 方法,您可能必须自己实现该 .equals()).通常 HashSet 开箱即用:它使用 Object.hashCode()Object.equals() 方法来比较对象.对于简单的对象,这应该足够独特.如果没有,您必须相应地实现 T.equals()T.hashCode().

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.

请参阅下面 Gaurav Saini 的评论,了解有助于实现 equals 和 hashcode 的库.

See Gaurav Saini's comment below for libraries helping to implement equals and hashcode.

这篇关于Java - 不同的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆