How to get a key from a map using a list as value
I am doing something like tags using Java Collections. I made a map using a list as value.
Can I get keyword searches from the list? How can i do this?
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("mammal");
list1.add("cute");
list2.add("mammal");
list2.add("big");
map.put("cat", list1);
map.put("dog", list2);
source to share
If I understand you correctly, you want to get the key assigned to one of the values ββin the list, stored as the corresponding value? Of course, you can always get all of these lists using an values()
interface method Map
and then iterate over them. However, how about having a second card where you use your tags as keys and keep a list of all the entries that contain that tag? For large datasets, this will probably work better.
source to share
There is no "magic" way to do this, you need to search within the values ββand then supply the correct key.
For example:
String str = "cute";
List<String> matchingKeys = map.entrySet().stream().filter( e -> e.getValue().contains(str))
.map(e -> e.getKey()).collect(Collectors.toList());
But you probably want to store your data in a different way arround, the list of "functions" being the key, and the meaning of the animal name.
source to share
If you want to get a set of tags use this method:
public Set<String> findMatchingKeys(Map<String, List<String>> map, String word){
Set<String> tags = new HashSet<String>();
for(Map.Entry<String,List<String> > mapEntry : map.entrySet()){
if(mapEntry.getValue().contains(word))
tags.add(mapEntry.getKey());
}
return tags;
}
source to share