Java How To Join Two Lists
There are many different ways to join two lists in Java.
Quick Answer - Just add one list to the other with the addAll() method:
list1.addAll(list2);
Additional Methods - Join Two Lists in Java
We are going to cover multiple different ways to join two lists. For each example that we cover we are going to assume that you have two existing lists defined and that they are setup like this:
List<String> list1 = new ArrayList<String>();
list1.add("abc");
list1.add("xyz");
list1.add("123");
List<String> list2 = new ArrayList<String>();
list2.add("apple");
list2.add("orange");
list2.add("kiwi");
Method 1:
You can create a third list. Add the first and second lists to it using the addAll() method.
List<String> list3 = new ArrayList<String>();
list3.addAll(list1);
list3.addAll(list2);
Method 2:
You can create a third list. Pass the first as a parameter to the constructor. Then add the second list using addAll().
List<String> list3 = new ArrayList<String>(list1);
list3.addAll(list2);
Method 3:
This may only work on Java 8 and up but I haven’t verified. ( only tested on 15 )
List<String> list3 = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
Method 4:
This uses an Apache Commons library.
List<String> list3 = ListUtils.union(list1, list2);
Method 5:
You can just add the second list directly to the first list and use that.
list1.addAll(list2);