0

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());
        }   
    }
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Jinxen
  • 83
  • 1
  • 8
  • What is "trainOverview"? Over a map you can iterate using Entry: http://stackoverflow.com/questions/46898/how-do-i-iterate-over-each-entry-in-a-map – arjacsoh Sep 04 '13 at 14:36

2 Answers2

3

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.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
1

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.

Fritz
  • 9,987
  • 4
  • 30
  • 49