Friday, July 1, 2022

How to Join Lists in Java

Sometimes we do have a need to join the lists constructed through different queries or received through different sources. This post shows different ways to join lists in Java which are as given below.

  1. Joining two lists in Java without using any API
  2. Joining lists in Java using addAll() method
  3. Joining lists using Apache Commons Collections

Joining two lists in Java without using any API

First thing that comes to mind in this scenario is loop the second list, retrieve the elements from the second list and add them to the first list thus creating a merged list. Some thing like this-

List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
List<String> anotherCityList = new ArrayList<String>();
anotherCityList.add("Hyderabad");
anotherCityList.add("Bangalore");
anotherCityList.add("Mumbai");    
for(int i = 0; i < anotherCityList.size() ; i++){
  cityList.add(anotherCityList.get(i));
}
for(String cityName : cityList){
  System.out.println("City Name " + cityName);
}

But why even write a loop and add elements one by one when there are better options to join lists in Java.

  • Using addAll() method provided by List interface.
  • Using ListUtils.union() method provided by Apache Commons Collections.

Joining lists in Java using addAll() method

You can use addAll() method to merge multiple lists. You can pass the list as an argument to the method to join it at the end of another list.

addAll​(Collection<? extends E> c)- addAll method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using addAll method, here adding with in the first list
    // we can create a new list and use addAll method to 
    // add both lists to the new List
    cityList.addAll(anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : cityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

Here addAll method is used to append second list to the first list, if there is a requirement that original lists should not be altered then you can create a new list and use addAll method to add both the lists to a new list.

Joining lists using Apache Commons Collections

Another way to join lists in Java is using ListUtils class in Apache Commons Collections. Only thing you need is to add commons-collections jar to your project. ListUtils class has a static method union to merge two lists.

According to the description of this method -

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

General form of union method

public static java.util.List union(java.util.List list1, java.util.List list2)

Though the name "union" may suggest otherwise please note that it will retain the duplicate elements in both the lists.

Let's see example code using this option to merge two (or more) lists in Java-

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using ListUtils.union
    List<String> newCityList = ListUtils.union(cityList, anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : newCityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

You can see that duplicates are retained when the union method is used. Name of the method union is a bit misleading as generally it suggests that duplicates will be counted once.

That's all for this topic How to Join Lists in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How and Why to Synchronize ArrayList in Java
  4. How to Remove Duplicate Elements From an ArrayList in Java
  5. How to Sort ArrayList in Java

You may also like-

  1. How HashMap Works Internally in Java
  2. How HashSet Works Internally in Java
  3. Covariant Return Type in Java
  4. Association, Aggregation And Composition in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Deadlock in Java Multi-Threading
  7. Synchronization in Java - Synchronized Method And Block
  8. Interface Default Methods in Java

1 comment: