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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java 8 stream Map> return map values if root map key contains without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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());
We are here to answer your question about Java 8 stream Map> return map values if root map key contains - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji