osek
osek

Reputation: 47

How to get key from map using list as a value

I am making something like tags using Java collections. I made a map using list as a value.

Can I get a key searching by words from list? How I can do that?

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

Upvotes: 3

Views: 4218

Answers (4)

mkuligowski
mkuligowski

Reputation: 1594

If you want to retrieve 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;
    }

Upvotes: 0

Zielu
Zielu

Reputation: 8552

There is no 'magic' way for it, you need to search inside the values and then report 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 other way arround, the list of "features" being the key, and the value the animal name.

Upvotes: 0

St&#233;phane Bruckert
St&#233;phane Bruckert

Reputation: 22903

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

Output if you search for "mammal":

mammal is in cat

mammal is in dog

Upvotes: 3

niceguy
niceguy

Reputation: 92

If I understand you correctly, you want to obtain the key given one of the value in the list stored as the corresponding value? Of course, you can always get all these lists using the values() method of the Map interface and then iterate over those. However, how about having a second map where you use your tags as keys and store a list of all the entries carrying this tag? For large data sets, this will probably perform better.

Upvotes: 3

Related Questions