-2

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.

  • Did you have an **attempt**? If yes, please share it and explain what problem you've encountered. A bare description of the task, like "transform one map into another", **isn't a problem**. If no, you're the one interested in trying it first. – Alexander Ivanchenko Aug 12 '22 at 15:24

2 Answers2

0

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.

MMZK1526
  • 654
  • 2
  • 16
0

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)
                        )
                ))
        ));
Danila Zharenkov
  • 1,720
  • 1
  • 15
  • 27