gpt4 book ai didi

java - 比较 hashmap 键中的 ArrayList

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:51 26 4
gpt4 key购买 nike

我有一个 String 类型的 HashMap , ArrayList<String> .两种不同keys存储在具有值列表的 HashMap 中。

现在我必须比较不同键的值并提取公共(public)值。如何实现这个功能?

以下是Hashmap的类型我正在使用:

示例列表:

{Size=[43, 53, 63, 48, 58], Color=[66, 62, 65, 64, 63]}

Here is code...

    private HashMap<String, ArrayList<String>> mapMatchvalues = new HashMap<>();

for (Map.Entry<String, ArrayList<String>> map3 : mapMatchvalues.entrySet()) {
List<String> getList1 = new ArrayList<>();
getList1 = map3.getValue();

for (int i = 0; i < getList1.size(); i++) {
if (getList.contains(getList1.get(i))) {
//Print values
} else {
// Print if not matched....
}
}
}

最佳答案

您可以使用 retainAll .如果您不想影响现有列表中的值,请使用新的 ArrayList

List<String> common = new ArrayList<>(mapMatchvalues.get("key1"));
common.retainAll(mapMatchvalues.get("key2"));

common 将包含列表中的匹配元素。

如果 map 中有多个条目,您可以遍历它

// initialize the common list with List
List<String> common = new ArrayList<>(mapMatchvalues.entrySet().iterator().next().getValue());
for (List<String> list : mapMatchvalues.values()) {
common.retainAll(list);
}

关于java - 比较 hashmap 键中的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49356908/

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