krackoder
krackoder

Reputation: 2981

Java iterate over nested maps of list

I have a map currently which is Map<String, Map<String, List<String>>>

I want to do an operation on each item in each nested list.

I can do it with lots of nested for-loops:

(EDIT - Updating parameters of performOperation function)

final Set<ResultType> resultSet = new HashSet<>();
for(Map.Entry<String, Map<String, List<String>>> topKeyEntry : inputNestedMap.entrySet()) {
    for (Map.Entry<String, List<String>> innerKeyEntry : topKeyEntry.getValue().entrySet()) {
        for (String listItem : innerKeyEntry.getValue()) {
            resultSet.add(performOperation(listItem, topKeyEntry.getKey(), innerKeyEntry.getKey()));
        }
    }
}

How do I do it with streams?

I tried it with nesting stream and apply map() and eventually calling the operation in the innermost map, but that results in an error saying there is a return missing.

I tried to flatten the entry list with flatMap() but could not get through.

Upvotes: 0

Views: 576

Answers (1)

WJS
WJS

Reputation: 40057

Based on your updated question, I have posted the following. It is essentially what you already have but in less cluttered form using the forEach method.

inputNestedMap.forEach((outerKey, innerMap) -> innerMap
        .forEach((innerKey, innerList) -> innerList.forEach(
                listItem -> resultSet.add(performOperation(
                            listItem, outerKey, innerKey)))));

And here is the modifed stream approach based on your changes. I would stick with the nested for loop solution.

Set<ResultType> resultSet= inputNestedMap.entrySet().stream()
    .flatMap(outerEntrySet-> outerEntrySet.getValue()
            .entrySet().stream() // flatten outer entrySet
            .flatMap(innerEntrySet -> innerEntrySet
                    .getValue().stream(). // flatten inner entrySet
                     map(lstVal->performOperation(lstVal, // perform the operation
                            outerEntrySet.getKey(), 
                            innerEntrySet.getKey())))).
                    collect(Collectors.toSet());  // return as as set

Upvotes: 1

Related Questions