如何从基于自定义 java 对象而不是原始类型的列表中删除重复项? [英] How to remove duplicates from a list based on a custom java object not a primitive type?
问题描述
在我发布这个问题之前,我发现以某种方式发布了here.但答案是基于字符串.但是,我在这里有不同的情况.我不是要删除字符串,而是要删除另一个名为 AwardYearSource 的对象.这个类有一个名为 year 的 int 属性.所以我想根据年份删除重复项.即如果不止一次提到 2010 年,我想删除那个 AwardYearSource 对象.我怎样才能做到这一点?
Before I post this question, I found somehow similar question posted here. But the answer was based on a String. However, I have a different situation here. I am not trying to remove String but another object called AwardYearSource. This class has an int attribute called year. So I want to remove duplicates based on the year. i.e if there is year 2010 mentioned more than once, I want to remove that AwardYearSource object. How can I do that?
推荐答案
最简单的基于字段移除元素的方法如下(保持顺序):
The simplest way to remove elements based on a field is as follows (preserving order):
Map<Integer, AwardYearSource> map = new LinkedHashMap<>();
for (AwardYearSource ays : list) {
map.put(ays.getYear(), ays);
}
list.clear();
list.addAll(map.values());
这篇关于如何从基于自定义 java 对象而不是原始类型的列表中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!