-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.

1
  • 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. Commented Aug 12, 2022 at 15:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.