Jinxen
Jinxen

Reputation: 83

Merging two lists without duplicates

I am currently trying to merge two lists while removing the duplicate values inside of them. However when doing this, adds every station and assumes that the mapValue List does not contain any of the stations even though it clearly does (Im ending up with a lot of duplicates). What am I doing wrong?

Map<String, List<Stations>> overview = new TreeMap<String, List<Stations>>();
    for(Trains train: trainOverview){
        List<Stations> mapValue = overview.get(train.getTrainNumber());
        //Merge lists if the key already exists, and replace the old value with the merged list
        if(overview.containsKey(train.getTrainNumber())){           
            for(Stations station: train.getStations()){
                if(!mapValue.contains(station)) mapValue.add(station);
            }
            overview.put(train.getTrainNumber(), mapValue);
        }
        //If no key exists, create a new entry
        else{
            overview.put(train.getTrainNumber(), train.getStations());
        }   
    }

Upvotes: 0

Views: 1554

Answers (2)

Fritz
Fritz

Reputation: 10045

In order for contains to return true, equals must be overridden in your Station class to make the check properly, otherwise the call goes up to Object's implementation that compares by reference.

If you want to keep on using Lists, check your equals implementation. If you don't have more than one station on each entry of the overview map, I suggest you switch to a Set that, by default, handles object uniqueness. You'll still have to provide a valid implementation for equals tough.

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

Uniqueness of elements within a collection can be achieved using a Set implementation. You should use it. First iterate over the element of your first list and add them to a set. Then repeat the same procedure for the second list. It's done.

Upvotes: 3

Related Questions