如何从列表基于自定义Java对象不是原始类型上删除重复?

问题描述:

在我发布这个问题,我发现了贴在某种程度上类似的问题here.但得到的答复是基于一个字符串。不过,我有一个不同的情况在这里。我不是试图消除字符串,但所谓的AwardYearSource另一个对象。这个类有一个名为一年一个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?

基于字段删除元素的最简单方法如下(preserving顺序排列):

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