Tuesday, 15 September 2015

Joining lists in Java

Some time we do have a need to join/merge the lists constructed through different queries or received through different sources. Though the first thing that comes to mind in this scenario is loop the second list, retrieve its elements and add them to the first 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 List provides a method addAll to do that.

According to Java Docs

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.

General form of addAll

addAll(Collection<? extends E> c)

There is another way to do that using Apache Commons Collections. Only thing is we need to add commons-collections jar to our project. It provides a ListUtils class which 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 the two lists.

Let's see some example code using the above two options to merge two (or more) lists -

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
        System.out.println("Using ListUtils.union");
        List<String> newCityList = ListUtils.union(cityList, anotherCityList);
        for(String cityName : newCityList){
            System.out.println("City Name " + cityName);
        }
        
        // 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
        System.out.println("Using addAll method");
        cityList.addAll(anotherCityList);
        for(String cityName : cityList){
            System.out.println("City Name " + cityName);
        }
    }
}

Output

Using ListUtils.union
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai
Using addAll method
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, union is a bit misleading as generally it suggests that duplicates will be counted once.
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 lists to the new list.

That's all for this topic Joining 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 HashMap internally works in Java
  3. How HashSet works internally in Java
  4. How to remove elements from an ArrayList in Java
  5. How to loop/iterate an arraylist in Java
  6. How to sort arraylist of custom objects in Java
  7. Java Collections interview questions

You may also like -

No comments:

Post a Comment