Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy map to another new map

I have 2 HashMap as follow:

@Session
private Map< Integer, List< ObjectA >> keyMap;

@Session
private Map< Integer, List< ObjectA >> keyMap2;

At first, I will put some data inside keyMap, and then I try to store the data inside keyMap to keyMap2:

keyMap2 = keyMap;

And then, I will edit some data inside keyMap. However, the value inside keyMap2 will changes as what I have edit in keyMap.

As I understanding, it is because keyMap2 is only point to keyMap pointer, so anything change in keyMap, it will reflect in keyMap2, because same pointer. (Please correct me if I am wrong.)

I wish to keep the keyMap2 value without changes like keyMap. Any idea other than I loop keyMap and put 1 by 1 inside keyMap2.

like image 254
Panadol Chong Avatar asked May 05 '26 05:05

Panadol Chong


2 Answers

keyMap2 = new HashMap<Integer, List<ObjectA>>(keyMap);

Swap out HashMap for whatever Map implementation you prefer or require.

like image 93
yojake42 Avatar answered May 09 '26 12:05

yojake42


You can copy using Java 8 Stream like this.

    Map<String, List<ObjectA>> keyMap2 = keyMap.entrySet().stream()
        .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), new ArrayList<>(e.getValue())))
        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

This code copies the lists of the values of keyMap.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!