Want to learn how to merge two ArrayLists in Java? In this post, we will cover the following ways:
- Using the List.addAll() method
- Using the Java 8 Streams
- Using the ListUtils.union() method
Merge two ArrayLists in Java using the List.addAll() method
There is addAll() method from the List interface that appends all of the elements in the specified collection to the end of the list. If you’re new to interfaces in Java, be sure to check out our tutorial on Interface in Java for a deeper understanding.
Example
class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Megan"); names.add("Steve"); List<String> names2 = new ArrayList<>(); names2.add("Melissa"); names2.add("Tom"); // add elements from list2 to list1 names.addAll(names2); System.out.println(names); } }
Join two ArrayLists using the Java 8 Streams
We can also use the Java 8 Streams API and the concat() operation to join two input streams in a single stream and then collect stream elements to an ArrayList.
Example
class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Megan"); names.add("Steve"); List<String> names2 = new ArrayList<>(); names2.add("Melissa"); names2.add("Tom"); List<String> combinedNames = Stream.concat(names.stream(), names2.stream()) .collect(Collectors.toList()); System.out.println(combinedNames); } }
Using the ListUtils.union() method to join two ArrayLists in Java
ListUtils class from the Apache Commons library has the union() method which combines two lists into a new one.
If you are using Maven project, than add this dependency to your pom.xml:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.4</version> </dependency>
Example
class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Megan"); names.add("Steve"); List<String> names2 = new ArrayList<>(); names2.add("Melissa"); names2.add("Tom"); List<String> combinedNames = ListUtils.union(names, names2); System.out.println(combinedNames); } }