How to copy HashMap (not shallow copy) in Java

后端 未结 5 943
情书的邮戳
情书的邮戳 2020-11-30 04:32

I need to make a copy of HashMap > but when I change something in the copy I want the original to stay the same. i.e w

5条回答
  •  天命终不由人
    2020-11-30 05:02

    This does need iteration unfortunately. But it's pretty trivial with Java 8 streams:

    mapCopy = map.entrySet().stream()
        .collect(Collectors.toMap(e -> e.getKey(), e -> List.copyOf(e.getValue())))
    

提交回复
热议问题