Converting between Java List and Array
0 CommentsLast Updated on June 30, 2019 by Simanta
It’s a fairly common task as a Java developer to convert from a List to an Array or from an Array to a list.
In one of my previous post, I discussed about converting Map to List.
Like many things in Java, there is often more than one way to accomplish a task. In this post, I’ll discuss various approaches of converting data between List objects and arrays.
Converting List to Array
The List
interface comes with a toArray()
method that returns an array containing all of the elements in this list in proper sequence (from first to last element). The type of the returned array is that of the array that you pass as parameter.
A ListToArrayConvertor
class that converts a List
to an array is this.
ListToArrayConvertor.java
import java.util.List; public class ListToArrayConvertor { public String[] convert(List<String> list){ return list.toArray(new String[list.size()]); } }
I have written a JUnit test case to test the convert()
method.
If you are new to JUnit, I would suggest going through my series of posts on JUnit.
The test class, ListToArrayConvertorTest
is this.
ListToArrayConvertorTest.java
package springframework.guru; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class ListToArrayConvertorTest { ListToArrayConvertor listToArrayConvertor; List<String> stringList; List<Integer> integerList; @Before public void setUp(){ listToArrayConvertor=new ListToArrayConvertor(); /*List of String*/ stringList = new ArrayList<>(); stringList.add("Java"); stringList.add("C++"); stringList.add("JavaScript"); stringList.add("TypeScript"); /*List of Integer*/ integerList = new ArrayList<>(); integerList.add(21); integerList.add(12); integerList.add(3); } @After public void tearDown(){ listToArrayConvertor=null; stringList=null; integerList=null; } @Test public void convert() { String[] languages = listToArrayConvertor.convert(stringList); assertNotNull(languages); assertEquals(stringList.size(),languages.length); } }
The test case calls the convert()
method of the ListToArrayConvertor
class and asserts two things. First it asserts that the array returned by the convert()
method is not null
. Second it asserts that the array contains the same number of elements as that of the list passed to the convert()
method.
Converting List to Array using Java 8 Stream
With the introduction of Streams in Java 8, you can convert a List
into a sequential stream of elements. Once you obtain a stream as a Stream
object from a collection, you can call the Stream.toArray()
method that returns an array containing the elements of this stream.
The code to convert a List
to an array using stream is this.
public String[] convertWithStream(List<String> list){ return list.stream().toArray(String[]::new); }
The JUnit test code is this.
@Test public void convertWithStream() { String[] languages = listToArrayConvertor.convertWithStream(stringList); assertNotNull(languages); assertEquals(stringList.size(),languages.length); }
Converting List to Primitive Array
When you call the List.toArray()
method, you get wrapper arrays, such as Integer[]
, Double[]
, and Boolean[]
. What if you need primitive arrays, such as int[]
, double[]
, and boolean []
instead?
One approach is to do the conversion yourself, like this.
public int[] convertAsPrimitiveArray(List<Integer> list){ int[] intArray = new int[list.size()]; for(int i = 0; i < list.size(); i++) intArray[i] = list.get(i); return intArray; }
The second approach is to use Java 8 Stream, like this.
int[] array = list.stream().mapToInt(i->i).toArray();
Another approach to convert a List
to a primitive array is by using Apache Commons Lang.
Converting List to Primitive Array with Apache Commons Lang
Apache Commons Lang provides extra methods for common functionalities and methods for manipulation of the core Java classes that is otherwise not available in the standard Java libraries.
To use Commons Lang, add the following dependency to your Maven POM.
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
Commons Lang comes with an ArrayUtils
class meant specifically to perform operations on arrays. Out of the several methods that ArrayUtils
provide, the methods of our interest are the overloaded toPrimitives()
methods. Each of these overloaded methods accepts a wrapper array and returns the corresponding primitive array.
The code to convert a List
to a primitive array using Commons Lang is this.
public int[] convertWithApacheCommons(List<Integer> list){ return ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()])); }
The test code is this.
@Test public void convertWithApacheCommons() { int[] numbers = listToArrayConvertor.convertWithApacheCommons(integerList); assertNotNull(numbers); assertEquals(integerList.size(),numbers.length); }
Converting List to Primitive Array with Guava
Guava is a project developed and maintained by Google that comprise of several libraries extensively used by Java developer. To use Guava
, add the following dependency to your Maven POM.
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>25.0-jre</version> </dependency>
Guava
contains several classes, such as Ints
, Longs
, Floats
, Doubles
, and Booleans
with utility methods that are not already present in the standard Java wrapper classes. For example, the Ints
class contains static utility methods pertaining to int
primitives.
The Guava
wrapper classes come with a toArray()
method that returns a primitive array containing each value of the collection passed to it.
The code to convert a List
to a primitive array using Guava
is this.
public int[] convertWithGuava(List<Integer> list){ return Ints.toArray(list); }
The test code is this.
@Test public void convertWithGuava() { int[] languages = listToArrayConvertor.convertWithGuava(integerList); assertNotNull(languages); assertEquals(integerList.size(),languages.length); }
Converting Array to List
To convert an array to a List
, you can use the Arrays.asList()
method. This method returns a fixed-size list from the elements of the array passed to it.
An ArrayToListConverter
class that converts an array to a List
is this.
ArrayToListConverter.java
package springframework.guru; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayToListConverter { public List<String> convert(String[] strArray){ return Arrays.asList(strArray); } }
The JUnit test class is this.
ArrayToListConverterTest.java
package springframework.guru; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class ArrayToListConverterTest { ArrayToListConverter arrayToListConverter; String[] stringArray; int[] intArray; @Before public void setUp(){ arrayToListConverter = new ArrayToListConverter(); /*initialize array of String*/ stringArray = new String[]{"Java","C++","JavaScript","TypeScript"}; /*initialize array of int*/ intArray = new int[]{21,12,3}; } @After public void tearDown(){ arrayToListConverter=null; stringArray=null; intArray=null; } @Test public void convert() { List<String> languageList = arrayToListConverter.convert(stringArray); assertNotNull(languageList); assertEquals(stringArray.length,languageList.size()); } }
Converting Array to List using Commons Collection
Commons Collection, similar to Commons Lang is part of the larger Apache Commons project. Commons Collection builds upon the Java collection framework by providing new interfaces, implementations, and utilities.
Before using the Commons Collection in your code, you need this dependency in your Maven POM.
<dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency>
CollectionUtils
is one class in Commons Collection that provides utility methods and decorators for Collection
instances. You can use the addAll()
method of CollectionUtils
to convert an array to a List
. This method takes as parameters a Collection
and an array. This method adds all the elements present in the array to the collection.
The code to convert an array to a List using the CollectionUtils
class of Commons Collection is this.
public List<String> convertWithApacheCommons(String[] strArray){ List<String> strList = new ArrayList<>(strArray.length); CollectionUtils.addAll(strList, strArray); return strList; }
The test code is this.
@Test public void convertWithApacheCommons() { List<String> languageList = arrayToListConverter.convertWithApacheCommons(stringArray); assertNotNull(languageList); assertEquals(stringArray.length,languageList.size()); }
Converting Array to List using Guava
Guava comes with a Lists
class with static utility methods to work with List
objects. You can use the newArrayList()
method of the Lists
class to convert an array to a List
. The newArrayList()
method takes an array and returns an ArrayList
initialized with the elements of the array.
The code to convert an array to a List
using the Lists
class of Guava is this.
public List<String> convertWithGuava(String[] strArray){ return Lists.newArrayList(strArray); }
The test code is this.
@Test public void convertWithGuava() { List<String> languageList = arrayToListConverter.convertWithGuava(stringArray); assertNotNull(languageList); assertEquals(stringArray.length,languageList.size()); }