JPM
JPM

Reputation: 93

How can I get the a key given a value in a Map<String, List<String>>?

Given a Map with the following structures {group2=[form4], group1=[form1, form2, form3]} how can I get the key(groupN) based on a value(formN)? Basically if one of the entries has a match with my input form I want to get that entry's key to set as the new form.

I was thinking of something like this:

newForm= formAliasList.entrySet()
        .stream()
        .filter(entry -> form.toLowerCase().equals(entry.getValue()))
        .map(Map.Entry::getKey)
        .findFirst().get();

Upvotes: 1

Views: 41

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40048

Since the value in Map<String, List<String>> is List<String>, you can simply check the formN existed in List using contains, and then collect the key of entry

newForm = formAliasList.entrySet()
                      .stream()
                      .filter(entry -> entry.getValue().contains(form.toLowerCase()))
                      .findFirst().map(Map.Entry::getKey).orElse(null);

Upvotes: 1

Related Questions