gpt4 book ai didi

java - 从Java中的多个列表中获取所有重复值

转载 作者:行者123 更新时间:2023-12-02 19:05:34 26 4
gpt4 key购买 nike

我想从多个整数列表中获取所有重复的值。令人困惑的部分是这些整数列表位于像这样的 Map of Map 中 LinkedHashMap > streams

// sample value
{
break_desc100=
{
bDesc_1000=[62, 72, 82, 92, 102, 112, 122],
bDesc 1001=[180, 190, 200, 210, 220, 230, 240],
cMessage_1000=[112],
cMessage_1001=[232]
}
}
// for this one I want to get 112

到目前为止,我尝试使用 retainAll,但如果重复项列表彼此不相邻,我的代码将无法正常工作。

for (Map.Entry<String,LinkedHashMap<String,List<Integer>>> entry : streams.entrySet()) {
String currentStream = entry.getKey();
LinkedHashMap<String,List<Integer>> bDescList = entry.getValue();
for (Map.Entry<String,List<Integer>> bDesc : bDescList.entrySet()) {
if (firstIteration) {
prevBDesc = bDesc;
firstIteration = false;
} else {
List<Integer> currentList = prevBDesc.getValue();
List<Integer> nextList = bDesc.getValue();
duplicates = new ArrayList<Integer>(currentList);
duplicates.retainAll(nextList);
allDuplicates.addAll(duplicates); //Set<Integer>
prevBDesc = bDesc;
}
}
}

编辑:对不起伙计们,我忘了补充说它是在 Java 1.5 上运行的。

最佳答案

编辑

这假设您正在寻找任何重复值。这包括在同一列表中查找重复项。如果我误解了这个问题,请纠正我。


您可以在 O(N) 时间和 O(N) 空间内完成此操作,方法是遍历嵌套哈希,同时计算每个整数的出现次数。然后我们可以过滤出多次出现的整数。

Map<String, List<Integer>> innerMap = new HashMap<>();
innerMap.put("bDesc_1000", Arrays.asList(62, 72, 82, 92, 102, 112, 122));
innerMap.put("bDesc_1001", Arrays.asList(180, 190, 200, 210, 220, 230, 240));
innerMap.put("cMessage_1000", Collections.singletonList(112));
innerMap.put("cMessage_1001", Collections.singletonList(232));

Map<String, Map<String, List<Integer>>> map = new HashMap<>();
map.put("break_desc100", innerMap);

Map<Integer, Integer> occurrenceMap = new HashMap<>();
map.forEach((outerKey, outerValue) -> {
outerValue.forEach((innerKey, innerValue) -> {
innerValue.forEach((element -> occurrenceMap.merge(element, 1, Integer::sum)
));
});
});

List<Integer> duplicates = occurrenceMap.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(duplicates);

输出

[112]

关于java - 从Java中的多个列表中获取所有重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65096800/

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