Home > database >  Converting a nested HashMap with a list to another nested HashMap with a linkedHashMap instead of th
Converting a nested HashMap with a list to another nested HashMap with a linkedHashMap instead of th

Time:08-13

I have a map in java that is an instance of the following:

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. I also want to preserve the order in the list to the 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.

CodePudding user response:

Please try this. Assume the first map is foo and the second map (with LinkedHashMap) is 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.

I may make some silly mistake in the implementation above, please do comment and edit in that case.

CodePudding user response:

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)
                        )
                ))
        ));
  • Related