0

我目前正在尝试合并两个列表,同时删除其中的重复值。然而,当这样做时,添加每个站点并假设 mapValue 列表不包含任何站点,即使它显然包含(我最终有很多重复项)。我究竟做错了什么?

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());
        }   
    }
4

2 回答 2

3

可以使用实现来实现集合中元素的唯一性Set。你应该使用它。首先遍历第一个列表的元素并将它们添加到集合中。然后对第二个列表重复相同的过程。完成。

于 2013-09-04T14:34:08.887 回答
1

为了containsreturn trueequals必须在您的Station类中重写以正确进行检查,否则调用将转到Object通过引用进行比较的 的实现。

如果您想继续使用Lists,请检查您的equals实现。如果您在地图的每个条目上没有多个站点overview,我建议您切换到Set默认情况下处理对象唯一性的站点。您仍然必须提供有效的实现equals

于 2013-09-04T14:37:29.957 回答