Java 8 stream Map> return map values if root map key contains

I have a map of maps:

Map<String, Map<String, Integer>> rootMap

and I want to return the rootMap values Map<String, Integer> if rootMap key contains stringValue using stream.

I tried:

rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

but I get Map<Object, Object> instead of Map<String, Integer>

Update #1

// it's a class with one field and a helper method
// @Data is a Lombok annotation
@Data
public class A {

    public Map<String, Map<String, Integer>> rootMap;

    public Map<String, Integer> getValuesByKey(String stringValue) {
        return rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    }
}

Answer

Here is your expression:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().contains(stringValue))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Here is your goal:

and I want to return the rootMap values Map<String, Integer> if rootMap key contains stringValue using stream.

Recall that map keys must be unique. You can’t have more than one Map.Entry of the same instance with the same key. Therefore, you can obtain the Map<String, Integer> corresponding to the key in rootMap whose value is stringValue as follows:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().equals(stringValue))
    .map(e -> e.getValue())
    .findAny()
    .get();

To defend against an error in the case that the key does not exist in rootMap you can use this version:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().equals(stringValue))
    .map(e -> e.getValue())
    .findAny()
    .orElse(Collections.emptyMap());

Leave a Reply

Your email address will not be published. Required fields are marked *