Sometime, we need to merge multiple list into one before performing any operation, say Iteration or transformation. It's quite common to merge two list, or combine them into a bigger list and there are multiple ways to do it. In this article, we will take a look at two simple way to join two list in Java, you can further extend that idea to join any number of List or it's implementation e.g. ArrayList or LinkedList in Java. One way to merge multiple list is by using addAll() method of java.util.Collection class, which allows you to add content of one List into another List. By using addAll() method you can add contents from as many List as you want, it's best way to combine multiple List. One thing to remember is that, it also preservers the order on which objects from List are added, it actually appends at the end of collection. So if you add List1 and than List2, content of List1 will come before elements of List2. You can even use this technique to combine multiple List into a Set to remove any duplicates. Another way of merging ArrayList is using Apache Commons Collection, Apart from several goodies, like creating union of Set in Java, it provides a ListUtils class with a union method, which can be used to create union of two List in Java. Result of previous operation and this is same, It also preservers the order and appends elements of second List after elements of first List.
Java Code example to merge multiple List
Here is full code example of joining two List in Java. In this example, we have two List of Integers, one containing numbers in hundred series, while other contains numbers in thousands series. In order to merge these two, we create an ArrayList and used addAll() method to append objects form second List. In second way, we have used ListUtils.union() method to combine two Lists.
That's all on this tutorial about merging two List in Java using JDK and Apache Commons Collections library. It's a very useful trick and can be useful in several cases. You can even extend this idea to create a Set of unique elements from multiple List as well, addAll() method from Collection, accepts any Collection implementation including ArrayList, LinkedList etc.