简体   繁体   中英

Get Key from Value in Map with Arraylist?

I´m writing a programm in Java. I decided to use a Map in connection with an ArrayList.

public static Map<String, List<String>> users = new HashMap<>();

So, my question is not that complicated I think: As you can see, there is a Key (String) and every Key has an own ArrayList. I´ve got a method, which gets one value of my Map (users). The method isn´t that important. But now I want to know, which key(String) belongs to my value, which the method found?

Without maintaining a different collection acting as a kind of index (probably overkill), there is no better way to do it than to iterate through all of the entries.

Using streams

final String searchTerm = "whatever";
final String user = users.entrySet().stream()
    .filter(entry -> entry.getValue().contains(searchTerm))
    .findFirst()
    .map(Map.Entry::getKey)
    .orElseThrow(() -> new RuntimeException("No matching user for " + searchTerm));

Imperative style

String user = null;
for (Map.Entry<String, List<String>> entry : users.entrySet())
{
    if (entry.getValue().contains(searchTerm))
    {
        user = entry.getKey();
        break;
    }
}
if (user == null)
{
    throw new RuntimeException("No matching user for " + searchTerm); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM