In this short code example I am going to share with you how to concatenate two ArrayList in Java.
Concatenate ArrayList using addAll() function
Let’s say we have these two ArrayList(s):
List<String> itemsList1 = new ArrayList(Arrays.asList("One", "Two")); List<String> itemsList2 = new ArrayList(Arrays.asList("Three", "Four"));
To concatenate the two lists together we can create a new ArrayList, and then use addAll() function to add to it all elements from itemList1 and then add all elements from itemList 2 like so:
List<String> mergedList = new ArrayList(); mergedList.addAll(itemsList1); mergedList.addAll(itemsList2); System.out.println("Merged list " + mergedList);
Concatenate ArrayList using Stream API
There are also a couple of ways to join two lists together using Java Stream API. In the below two examples I am going to use same two ArrayList(s) used in the example above:
List<String> itemsList1 = new ArrayList(Arrays.asList("One", "Two")); List<String> itemsList2 = new ArrayList(Arrays.asList("Three", "Four"));
Concatenate using Stream.concat
In this example I am also using the distinct() to filter out all duplicates.
List<String> mergedList2 = Stream.concat(itemsList1.stream(), itemsList2.stream()) .distinct() .collect(Collectors.toList()); System.out.println("Merged list 2 " + mergedList2);
Concatenate using Stream.of and forEach
List<Object> mergedList3 = new ArrayList<>(); Stream.of(itemsList1, itemsList2).forEach(mergedList3::addAll); System.out.println("Merged list 3 " + mergedList2);
I hope this example is helpful!
Checkout the below Java books and video courses which you might also find helpful.
Java Video Lessons