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?
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}}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With