Last active
May 27, 2023 16:44
-
-
Save sshark/81354b18708fa8c4579eb5436a24fcbd to your computer and use it in GitHub Desktop.
deep copy list of maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class ListMapDeepCopy { | |
static <A, B> void deepCopy(List<Map<A,B>> target, List<Map<A,B>> source ) { | |
target.clear(); | |
source.forEach(m -> target.add(new HashMap<>(m))); | |
} | |
public static void main(String[] args) { | |
Map<String, Integer> foobar1 = new HashMap<>(); | |
foobar1.put("foo1", 1); | |
foobar1.put("bar1", 2); | |
Map<String, Integer> foobar2 = new HashMap<>(); | |
foobar2.put("foo2", 10); | |
foobar2.put("bar2", 20); | |
List<Map<String, Integer>> maps1 = new ArrayList<>(); | |
maps1.add(foobar1); | |
maps1.add(foobar2); | |
List<Map<String, Integer>> maps2 = new ArrayList<>(); | |
deepCopy(maps2, maps1); | |
System.out.println("--- maps 1 ---"); | |
maps1.stream().forEach(System.out::println); | |
System.out.println("--- maps 2 ---"); | |
maps2.stream().forEach(System.out::println); | |
maps1.get(1).put("xyz2", 30); | |
System.out.println("--- maps 1 ---"); | |
maps1.stream().forEach(System.out::println); | |
System.out.println("--- maps 2 ---"); | |
maps2.stream().forEach(System.out::println); | |
maps1.remove(1); | |
System.out.println("--- maps 1 ---"); | |
maps1.stream().forEach(System.out::println); | |
System.out.println("--- maps 2 ---"); | |
maps2.stream().forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment