简体   繁体   English

Java 迭代列表的嵌套映射

[英]Java iterate over nested maps of list

I have a map currently which is Map<String, Map<String, List<String>>>我有一个 map 目前是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:我可以用很多嵌套的 for 循环来做到这一点:

(EDIT - Updating parameters of performOperation function) (编辑 - 更新 performOperation 函数的参数)

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.我尝试嵌套stream并应用map()并最终调用最里面的 map 中的操作,但这会导致错误提示缺少返回值。

I tried to flatten the entry list with flatMap() but could not get through.我试图用flatMap()来展平条目列表,但无法通过。

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.它本质上是您已经拥有的,但使用forEach方法以更简洁的形式出现。

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.这是根据您的更改修改后的 stream 方法。 I would stick with the nested for loop solution.我会坚持使用嵌套的 for 循环解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM