简体   繁体   English

如何将数组列表与Hasmap进行比较并根据值从Hashmap获取密钥?

[英]How to compare arraylist with Hasmap and get the key from Hashmap based on value?

I've got list : 我有清单:

ArrayList<String> list = new ArrayList<>();

and map : 和地图:

Map<String, List<String>> map = new HashMap<>();

I need to compare values of the list and map and return key based on that value 我需要比较列表和地图的值,并根据该值返回键

The problem is that I dont know how to synchronize iterations as arraylist has smaller size as each list in map. 问题是我不知道如何同步迭代,因为arraylist的大小比map中的每个列表小。

Also I tried this method : 我也尝试了这种方法:

public static Object getKeyByValue(Map<String,List<String>> map, String value) {
    for (Entry<String, List<String>> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

getKeyByValue(map,list.get(0)); 

..but this call retuned false even If there is certain value... ..但是即使有一定的价值,这个电话也被重新设置为假...

Any ideas how get each key for each value? 有什么想法如何获取每个值的每个键? Thank you very much 非常感谢你

You are comparing a List<String> to a String , so it would never return true. 您正在将List<String>String进行比较,因此它永远不会返回true。

Use List.contains instead, to determine if the String appears in the List : 改用List.contains确定String出现在List

    if (entry.getValue().contains(value)) {
        return entry.getKey();
    }

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

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