Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates ArrayList custom object [duplicate]

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?

like image 419
Nicolas Zawada Avatar asked Apr 30 '15 10:04

Nicolas Zawada


People also ask

Can an ArrayList can hold duplicate objects?

An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.


1 Answers

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);
}
like image 67
Jordi Castilla Avatar answered Sep 20 '22 09:09

Jordi Castilla