繁体   English   中英

可以比较来自 Map 的值<integer, arraylist<string> &gt; 与 ArrayList<string></string></integer,>

[英]Can compare values from Map<Integer, ArrayList<String>> with ArrayList<String>

我创建了一个Map<Integer, ArrayList<String>> map并且我想将 map 中的每个值与一个ArrayList<String> likeList进行比较,如果它们匹配则获取密钥。 我会带上以后使用的钥匙。

我试图像这样运行我的代码,但它不起作用,因为它什么都不返回:

for (int key : map.keySet()) {
    if(map.get(key).equals(likeList)){
        index = key;
        Log.d("IndexN", String.valueOf(index));
    }
}

然后,我尝试了这个:

int index = 0;
for (Map.Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
    if(entry.getValue().equals(likeList)){
        index = entry.getkey();
    }
}

你有什么主意吗?

当我尝试上面的代码时,它不返回索引。

从这条评论中,我了解到,一旦您在 map 中找到匹配项,则应记录index并停止进一步处理。 换句话说,要么在likeList中只有一个 likeList 匹配,要么你想在 map 中找到likeList的第一个匹配。 如果是,您需要在找到匹配项后立即中断循环(如下所示)。

for (int key : map.keySet()) {
    if (map.get(key).equals(likeList)) {
        Log.d("IndexN", String.valueOf(index));
        break;
    }
}

请注意,这将为您提供相同的值,每次执行时,仅当 map 只有一个likeList或 map 是LinkedHashMap时。 如果它是HashMap并且它有多个likeList ,则每次执行它时可能会得到不同的值,因为HashMap不保证其条目的顺序。

但是,如果likeList中可能有多个 likeList 匹配,并且您想要记录所有匹配并获取相应键的列表,则可以执行以下操作:

List<Integer> indexList = new ArrayList<>();
for (int key : map.keySet()) {
    if (map.get(key).equals(likeList)) {
        Log.d("IndexN", String.valueOf(index));
        indexList.add(key);
    }
}

// Display the list of corresponding keys
System.out.println(indexList);

添加密钥列表以存储所有匹配项

List<Integer> indices = new ArrayList<>();
for (int key : map.keySet()) {
    if (map.get(key).equals(likeList)) {
        indices.add(key);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM