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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If your AwardYearSource class overrides equals and hashcode methods (Eclipse can generate both), then you can add them to a Set. The Set will not contain any duplicates.
The output is [2000]. Only one item in the set.
Create a HashMap object with int as the key type and your class as the value type. Then iterate over the list and insert each element to the map using:
Then remove all elements from the origianl list and iterate over the map and insert each element to the list.
The simplest way to remove elements based on a field is as follows (preserving order):
Another way would be to override
hashCode()
andequals(Object obj)
for your object. Since it just has one field you want to use to determine equality, this is pretty straightforward. Something like:Then you can just stick all of the objects into a
Set
to remove duplicates:Fairly simply. Although something bugs me about the map versions (not that I doubt they'd work, it just seems like overkill, somehow - although this version isn't necessarily any better in that regard).
Answer is functional, and threadsafe (assuming
AwardYearSource
is immutable).You could use a map and store your objects with the year as a key:
At the end the map will contain unique values by year, which you can call with the values method: