A handy solution for performing a shallow copy of HashMap relies on the HashMap constructor, HashMap(Map<? extends K,? extends V> m). The following code is self-explanatory:
Map<K, V> mapToCopy = new HashMap<>();
Map<K, V> shallowCopy = new HashMap<>(mapToCopy);
Another solution may rely on the putAll(Map<? extends K,? extends V> m) method. This method copies all of the mappings from the specified map to this map, as shown in the following helper method:
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> shallowCopy(Map<K, V> map) {
HashMap<K, V> copy = new HashMap<>();
copy.putAll(map);
return copy;
}
We can also write a helper method in Java 8 functional style as follows:
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> shallowCopy(Map<K, V> map) {
Set<Entry<K, V>> entries = map.entrySet();
HashMap<K, V> copy = (HashMap<K, V>) entries.stream()
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue));
return copy;
}
However, these three solutions only provide a shallow copy of the map. A solution for obtaining a deep copy can rely on the Cloning library (https://github.com/kostaskougios/cloning) introduced in Chapter 2, Objects, Immutability, and Switch Expressions. A helper method that will use Cloning can be written as follows:
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> deepCopy(Map<K, V> map) {
Cloner cloner = new Cloner();
HashMap<K, V> copy = (HashMap<K, V>) cloner.deepClone(map);
return copy;
}