0

I have one Map like this.

Map<Object,Map<Object,Map<Object,Object>>> mapCurrentMap

And another map:

Map<Object,Map<Object,Map<Object,Object>>> copyCurrentMap

Now, I want copy all data from mapCurrentMap to copyCurrentMap and when I change data in copyCurrentMap then data in mapCurrentMap should not change. I used putAll of HashMap but it's return result is not what I want. So, some one help you.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79

1 Answers1

0

Please, try something like that:

Map<Object,Map<Object,Map<Object,Object>>> deepCopy(Map<Object,Map<Object,Map<Object,Object>>> src) {
    final Map<Object,Map<Object,Map<Object,Object>>> dst = new HashMap<Object, Map<Object, Map<Object, Object>>>();
    for (Object key : src.keySet()) {
        final HashMap<Object, Map<Object, Object>> copy = new HashMap<Object, Map<Object, Object>>();
        final Map<Object, Map<Object, Object>> innerMap = src.get(key);
        for (Object innerKey : innerMap.keySet()) {
            Map<Object,Object> innerCopy = new HashMap<Object, Object>(innerMap.get(innerKey));
            copy.put(innerKey, innerCopy);
        }
        dst.put(key, copy);
    }
    return dst;
}

I'm not really sure that it's working, but I think you get the idea... you have to copy Map<Object,Object> to another Map<Object,Object> on the lowest level, all levels above needs to be "get from original -> put to copy with the same key".

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
  • > thank you for support. But if my map like that: Map>>>>> mapCurrentMap so if use "for" so long. – yen dau Nov 07 '15 at 03:32
  • I don't see any other solution. The idea is that you have to have new references everywhere, that are not the references of initial maps. I can not imagine how it's possible without running through all the object's tree. – Andrej Istomin Nov 07 '15 at 03:37
  • Sorry, I think I misunderstood your comment. "Long", you mean, not performance(what I understood), but lines of code. If so, you can use recursion in the similar way as described here: http://stackoverflow.com/a/9337639/1842599 – Andrej Istomin Nov 07 '15 at 03:57