简体   繁体   English

将带有列表的嵌套 HashMap 转换为带有linkedHashMap而不是列表的另一个嵌套 HashMap

[英]Converting a nested HashMap with a list to another nested HashMap with a linkedHashMap instead of the list

I have a map in java that is an instance of the following:我在 java 中有一个 map,它是以下示例:

Map< K1,Map< K2, List<Object>>>

I want to convert it to the following structure:我想将其转换为以下结构:

Map< K1, Map< K2, LinkedHashMap<Object, Value>>> 

Where Value is a property of Object.其中 Value 是 Object 的属性。 I also want to preserve the order in the list to the HashMap.我还想将列表中的顺序保留到 HashMap。

I found some similar code examples of what i am trying to achieve but not the same.我发现了一些我想要实现的类似代码示例,但不一样。 I appreciate any help i can get.我很感激我能得到的任何帮助。

Please try this.请试试这个。 Assume the first map is foo and the second map (with LinkedHashMap) is bar .假设第一个 map 是foo而第二个 map (带有 LinkedHashMap)是bar

         bar = new HashMap<>();
         for (var key1 : foo.keySet()) {
            bar.put(key1, new HashMap<>()); // key1 is of type K1
            var innerMap = foo.get(key1); // type: Map< K2, List<Object>>
            for (var key2 : innerMap.keySet()) { // key2 is of type K2
                bar.get(key1).put(key2, new LinkedHashMap<>());
                var innerLinkedMap = bar.get(key1).get(key2); // type: LinkedHashMap<Object, Value>; now empty
                for (var element : innerMap.get(key2)) {
                    innerLinkedMap.put(element, element.something); // insert in the order of the list
                }
            }
        }

Note that it only works if the elements in each list are unique, otherwise the same key would be re-inserted into the LinkedHashMap, which does not affect the insertion order.请注意,它仅在每个列表中的元素都是唯一的情况下才有效,否则相同的键将重新插入到 LinkedHashMap 中,这不会影响插入顺序。

I may make some silly mistake in the implementation above, please do comment and edit in that case.我可能在上面的实现中犯了一些愚蠢的错误,请在这种情况下进行评论和编辑。

It can be done using streams可以使用流来完成

map.entrySet().stream().collect(toMap(
                Map.Entry::getKey, // K1
                //transforming inner map
                e -> e.getValue().entrySet().stream().collect(toMap( 
                        Map.Entry::getKey, // K2
                        // iterating list and transforming it into linkedhashmap
                        es -> es.getValue().stream().collect( 
                                toMap(identity(),
                                      Obj::getValue,
                                      (a, b) -> b,
                                      LinkedHashMap::new)
                        )
                ))
        ));

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

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