Java8如何使用流和lambda将3级嵌套列表转换为嵌套HashMap

问题描述 投票:0回答:1

我正在尝试将3级嵌套列表转换为Nested HashMap。

相同的函数声明为:

Map<Key1, Map<Key2, List<String>>> transformToMap (List<Obj1> inputList)

inputList内部具有嵌套列表,又具有嵌套列表。

我编写的代码使用传统的for循环,如下所示:

private Map<Key1, Map<Key2, List<String>>> transformToMap (List<Obj1> inputList){

    Map<Key1, Map<Key2, List<String>>> resultMap = new HashMap<>();

    inputList.forEach(item ->{
        List<Obj2> list1 = item.getObj2List();

        list1.forEach(nestedItem ->{

            final String name = nestedItem.getName();
            nestedItem.getKeyList().forEach(key1 ->{

                Map<Key2, List<String>>  nestedMap = resultMap.get(key1);
                if(nestedMap == null){
                    nestedMap = new HashMap<>();
                }
                List<String> stringList = nestedMap.get(item);
                if(stringList == null){
                    stringList = new ArrayList<>();
                }

                stringList.add(name);
                nestedMap.put(item,stringList);
                resultMap.put(key1, nestedMap);

            });
        });
    });
    return resultMap;
}

上面的代码满足了我的期望。

使用Collectors.toMap将其转换为流λ的有效方法是什么?

lambda java-8 stream hashmap
1个回答
0
投票

您可以添加Stream.flatMap

resultMap.values().stream().
    flatMap(map -> map.values().stream())
    .flatMap(map -> map.stream()).forEach(nestedItem ->{
    // You code
    });
© www.soinside.com 2019 - 2024. All rights reserved.