How can I stream a Map of String and Map using java 8?

Viewed 90

I have a Map<Key1, Map<Key2, CustomObject>>. I need go through the Map, check if Key2.equals("a string") and return a Map<Key1, CustomObject>.

Is this possible with java 8? Should it be done with java 8 or is it better with nested for loops?

2 Answers

You can filter the entries of the input Map to keep only entries whose value contains the "a string" key. Then use Collectors.toMap to collect them into a new Map:

Map<Key1, CustomObject> map = 
    inputMap.entrySet()
            .stream()
            .filter(e -> e.getValue().containsKey("a string"))
            .collect(Collectors.toMap(Map.Entry::getKey,
                                      e -> e.getValue().get("a string")));

it also works

    Map<String, SocialCredentials> collect = configData.getData()
                .entrySet().stream()
                .map(map -> map.getValue()
                        .entrySet().stream()
                        .filter(entry -> 
                            profile.toLowerCase().equals(entry.getKey()))
                        .collect(Collectors.toMap(p -> map.getKey(), 
                                                   Map.Entry::getValue)))
                .collect(HashMap::new, Map::putAll, Map::putAll);

but your solution is more suitable in my case.

Related