简体   繁体   中英

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.

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.

Use List.contains instead, to determine if the String appears in the List :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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