I have an ArrayList which contains element of a class Event
.
Event has two properties, Name
and Timestamp
.
The list now shows ALL events.
I want to remove the duplicates with the same name, but different timestamp, and put them in another list. This way the user can click on an event with that name, then select a date.
I am already overriding the function equals (that compares name AND timestamp) for some other functionalities in my application.
How can I solve this?
An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.
If you already have your own equals method you can't use Hash
collections. You must manually check it implementing a nested loop:
List<Event> allEvents = // fill with your events.
List<Event> noRepeat = new ArrayList<Event>();
for (Event event : allEvents) {
boolean isFound = false;
// check if the event name exists in noRepeat
for (Event e : noRepeat) {
if (e.getName().equals(event.getName()) || (e.equals(event))) {
isFound = true;
break;
}
}
if (!isFound) noRepeat.add(event);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With