Skip to content
Advertisement

Filter Key from a hashmap Map<String, List> when a string matches one of the elements in the list

I’m fairly new to java in general so help is very appreciated.

I have a structure like this:

private Map<String, List<String>> campaign = new Hashmap<>();

This hashmap has values like this:

campaign = {   
   "John": {["1234"]},
   "Doe": {["5555","2222"]},
   "Smith": {["Smith"]}
}

I’m trying to filter the key of this hashMap when one of the elements matches an element of the list.

I’ve tried this so far based on similar solutions I found:

public String getKey(String id) {
    campaign.entrySet().stream()
    .filter(map -> map.getValue().stream().
    anymatch(list -> list.contains(id)))
    .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() ))
}
// I see toMap is not what I need but don't know what to use

I expecto to get: getKey(1234) = "John"

Advertisement

Answer

You may want to use findAny():

public String getKey(String id) {
    return campaign
        .entrySet()
        .stream()
        .filter(map -> map
            .getValue()
            .stream()
            .anyMatch(list -> list.contains(id))
        )
        .map(Entry::getKey) 
        .findAny()
        .orElse(null);
}

anyMatch() returns an Optional that contains any value of the (filtered) Stream (if it is present).

If you want to get the first element in the Stream, you could use findFirst instead but order is not relevant in most Maps anyways.

With .map, you can map the entry to its key.

In case you want to return all keys, you could use methods like toList or .toSet.

With orElse(null), you specify that null should be used if no matching entry/key was found.

As an alternatives to orElse, you could return the Optional or use orElseThrow if the value needs to be present.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement