Reputation: 35
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
Upvotes: 0
Views: 1558
Reputation: 393966
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();
}
Upvotes: 2