gpt4 book ai didi

java - 合并两个不重复的列表

转载 作者:行者123 更新时间:2023-12-01 18:44:07 24 4
gpt4 key购买 nike

我目前正在尝试合并两个列表,同时删除其中的重复值。然而,在执行此操作时,会添加每个站点并假设 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());
}
}

最佳答案

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

关于java - 合并两个不重复的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18616655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com