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);

      

+3


source to share


4 answers


for (Entry<String, List<String>> entry : map.entrySet()) {
    if (entry.getValue().contains(animalYouSearch)) {
        System.out.println(animalYouSearch + " is in " + entry.getKey());
    }
}

      

Conclusion, if you're looking for "mammal":



mammal is in cat

the mammal is in the dog

+3


source


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.



+3


source


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.

0


source


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;
    }

      

0


source







All Articles