Why conversion of array to list?
Often we need to convert an array to a list in java. This is mainly because of the following reasons

  • Arrays cannot be increased in size dynamically and you need a provision to grow it when it is full while a list increases its size automatically when it is full.
  • Array does not provide a provision to remove its element while with a list, it can be done easily.
  • If you need to check the presence of an element in array, then you need to iterate over it while a list provides a built-in method contains for this.

    contains will work when you have properly overridden hashcode and equals methods. To know more about overriding these, check this post.

  • You are receiving data from an external library and sending it to another service after some processing.
    Now the data received is in the form of array while that expected by the other end is a list, you have no choice but to convert array to list.

Any of the above scenario may arise in your code where you need a conversion of array to a list. This post will explain a couple of methods that can be used.

Method 1: Using Arrays class
java.util.Arrays class has an asList method which takes an array as argument and returns a list populated with the contents of the array.
This is a static method and can be called without any instance of java.util.Arrays class.
Example,

import java.util.Arrays;
import java.util.List;

public class ArrayToListConverter {

   public static void main(String[] args) {
      // create string array      
      String[] array = {"rainbow", "mountains", "ocean"};
      // convert it to a list
      List list = Arrays.asList(array);
      // print list
      System.out.println(list);
      // check if it is actually a list
      System.out.println(list instanceof List);
   }
}

Output of above program is

[rainbow, mountains, ocean] true

Note that instanceof returns true when checked against a java.util.List. Remember that the generic type of list will be the same as the type of array.

Remember that you cannot add a new element to the list returned by asList method.
Trying to add a new element will raise a java.lang.UnsupportedOperationException. This is because the list returned by asList method is a fixed size list.
If you need to add elements to the newly created list, then create a new list with the contents of the array as shown below.

// convert array to list
List list = Arrays.asList(array);
// create a new list with the contents of existing list
List newList = new ArrayList(list);
// add a new element to list
newList.add("river");

This method can only be used for object arrays and not for primitive arrays such as array of int, float, char or double.
Array of wrapper types such as Integer, Float, Double and Character should be used.
Method 2: Using Collections class
java.util.Collections class has an addAll method which takes another collection and an array as arguments and adds the elements of the array to the supplied collection.
Create a new and empty array list and pass it to addAll method along with the array. Contents of the array are copied into the list. Example,

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayToListConverter {

   public static void main(String[] args) {
      // create an array
      String[] array = {"rainbow", "mountains", "ocean"};
      // create an empty list
      List list = new ArrayList();
      // add array elements to list
      Collections.addAll(list, array);
      System.out.println(list);
   }
}

Above code will output

[rainbow, mountains, ocean]

If the collection(java.util.List in above example) or the array is null, then addAll will throw a java.lang.NullPointerException.

Method 3: Iterating over array
This is a traditional approach of converting an array to a list. In this method, create an empty list. Iterate over the array using a loop.
In every iteration, add the array element to the list using its add method. After the loop completes, list will have all the elements of the array.
Note that the generic type of list and array should be same.

import java.util.ArrayList;
import java.util.List;

public class ArrayToListConverter {

   public static void main(String[] args) {
      String[] array = { "rainbow", "mountains", "ocean" };
      // create an empty list
      List list = new ArrayList();
      // iterate over array
      for (String element : array) {
         // add array element to list
         list.add(element);
      }
      System.out.println(list);
   }
}

Output of above program is

[rainbow, mountains, ocean]

Method 4: Using stream in java 8
Java 8 introduced the concept of streams. Get a stream over the array using stream method of java.util.Arrays class which takes the array as argument.
Call collect method on the stream object. This method takes an object of type java.util.stream.Collectors object.
This class allows performing operations on the array such as adding them to a list, set or a map.
Its toList method returns a list consisting of the elements of the array.
Example,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ArrayToListConverter {

   public static void main(String[] args) {
      String[] array = { "rainbow", "mountains", "ocean" };
      // get a stream of array elements
      Stream stream = Arrays.stream(array);
      // get the array as list
      List list = stream.collect(Collectors.toList());
      System.out.println(list);
   }
}

Output is

[rainbow, mountains, ocean]

Above code can be converted to a one-liner as below

List list = Arrays.stream(array).collect(Collectors.toList());

Remember that the generic type of list should be the same as the type of array.
Hope the methods listed in this article were helpful. Do not forget the hit the clap button below.
Keep visiting, keep learning!!!

Leave a Reply