Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying a java treemap of treemap using putAll()

Tags:

java

copy

treemap

I have a TreeMap within a TreeMap.

TreeMap <String, TreeMap<String, Double>> x_probs_org = new TreeMap<String, TreeMap<String, Double>>();

But when I make another one with exactly the same definition, and then copy the first one:

x_probs.putAll(x_probs_org);

I notice the new treemap doesn't copy everything. It copies all the String keys correctly, but only the last element in the value (TreeMap). Is there any easier way to do this right, apart from scrolling through the entire first treemap and then adding the elements to the new one?

I just need to have identical data structures with identical data to begin with. What I did was to run the loop through which I populated the first treemap, and then simply put the next one with it, in the same loop. This didn't work either:

// build tempMap up there...
x_probs_org.put(tokens[0], tempMap);    
x_probs.put(tokens[0], tempMap);

x_probs insists on missing data that x_probs_org manages to get. Does "tempMap" get exhausted by populating something once?

like image 394
user961627 Avatar asked Oct 26 '25 02:10

user961627


1 Answers

This works for me:

public static void main(String[] args) {
    Map <String, Map<String, Double>> map = new TreeMap<String, Map<String, Double>>();
    Map<String, Double> innerMap = new TreeMap<String, Double>();
    innerMap.put("a", 1.0);
    innerMap.put("b", 2.0);
    map.put("inner1", innerMap);
    innerMap = new TreeMap<String, Double>();
    innerMap.put("c", 3.0);
    innerMap.put("d", 4.0);
    map.put("inner2", innerMap);

    Map <String, Map<String, Double>> newMap = new TreeMap<String, Map<String, Double>>();
    newMap.putAll(map);

    System.out.println(map); // prints {inner1={a=1.0, b=2.0}, inner2={c=3.0, d=4.0}}
    System.out.println(newMap); // prints {inner1={a=1.0, b=2.0}, inner2={c=3.0, d=4.0}}
}
like image 170
assylias Avatar answered Oct 28 '25 15:10

assylias