Can we convert list to array in Java?

DZone > Java Zone > How to Convert Between List and Array in Java

How to Convert Between List and Array in Java

Want to learn more about converting a list to an array in Java? Check out this tutorial to learn more using the Apache Commons Lang and Guava.

by
John Thompson
·
Aug. 01, 18 · Java Zone · Tutorial
Like (8)
Comment
Save
Tweet
119.25K Views

Its a fairly common task for a Java developer to convert a list to an array or from an array to a list. Like many things in Java, there is often more than one way to accomplish a task. In this post, Ill discuss the various approaches to converting data between list objects and arrays.

Converting List to Array

Thelistinterface comes with thetoArray()method that returns an array containing all of the elements in this list in proper sequence (from the first to last element). The type of returned array is that of the array that you pass as the parameter.

A ListToArrayConvertorclass that converts alistto an array is shown below:

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 theconvert()method. If you are new to JUnit, I would suggest going through my series of posts on JUnit. The test class,ListToArrayConvertorTestis demonstrated below:

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 theconvert()method of theListToArrayConvertorclass and asserts two things. First, it asserts that the array returned by theconvert()method is not null. Second, it asserts that the array contains the same number of elements as that of the list passed to theconvert()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 astreamobject from a collection, you can call theStream.toArray()method that returns an array containing the elements of this stream.

The code to convert alistto an array using stream is as follows:

public String[] convertWithStream(List<String> list){ return list.stream().toArray(String[]::new); }


The JUnit test code is shown below:

@Test public void convertWithStream() { String[] languages = listToArrayConvertor.convertWithStream(stringList); assertNotNull(languages); assertEquals(stringList.size(),languages.length); }


Converting List to Primitive Array

When you call theList.toArray()method, you get wrapper arrays, such as Integer[], Double[], andBoolean[]. What if you need primitive arrays, such as int[], double[], andboolean []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 the Java 8 stream:

int[] array = list.stream().mapToInt(i->i).toArray();


Another approach would be to convert alistto a primitive array by using theApache 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 are otherwise not available in the standard Java libraries.

To use the Commons Lang, add the following dependency to your Maven POM:

<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>


The Apache Commons Lang comes with anArrayUtilsclass that is meant specifically to perform operations on arrays. Out of the several methods thatArrayUtilsprovides, the methods of our interest are the overloadedtoPrimitives()methods. Each of these overloaded methods accepts a wrapper array and returns the corresponding primitive array.

The code to convert alistto a primitive array using the Commons Lang can be seen below:

public int[] convertWithApacheCommons(List<Integer> list){ return ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()])); }


The test code is as follows:

@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 and is comprised of several libraries that are extensively used by Java developers. 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, andBooleans,with utility methods that are not already present in the standard Java wrapper classes. For example, theintsclass contains static utility methods pertaining to int primitives.

The Guava wrapper classes come with atoArray()method that returns a primitive array containing each value of the collection passed to it.

The code to convert alistto a primitive array using Guava would look like this:

public int[] convertWithGuava(List<Integer> list){ return Ints.toArray(list); }


Here is the test code:

@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 theArrays.asList()method. This method returns a fixed-size list from the elements of the array passed to it.

AnArrayToListConverterclass that converts an array to alistcan be found below:

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>


CollectionUtilsis one class in the Commons Collection that provides utility methods and decorators for theforCollectioninstances. You can use theaddAll()method ofCollectionUtilsto convert an array to alist. This method takes the parameters of 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 theCollectionUtilsclass from the Commons Collection will look like this:

public List<String> convertWithApacheCommons(String[] strArray){ List<String> strList = new ArrayList<>(strArray.length); CollectionUtils.addAll(strList, strArray); return strList; }


Here is the test code:

@Test public void convertWithApacheCommons() { List<String> languageList = arrayToListConverter.convertWithApacheCommons(stringArray); assertNotNull(languageList); assertEquals(stringArray.length,languageList.size()); }


Converting Array to List Using Guava

Guava uses a listsclass with static utility methods to work withListobjects. You can use thenewArrayList()method of thelistsclass to convert an array to a list. The newArrayList()method takes an array and returns anArrayListthat has beeninitialized with the elements of the array.

The code to convert an array to alistusing thelistsclass of Guava will look like the following:

public List<String> convertWithGuava(String[] strArray){ return Lists.newArrayList(strArray); }


Here is the test code:

@Test public void convertWithGuava() { List<String> languageList = arrayToListConverter.convertWithGuava(stringArray); assertNotNull(languageList); assertEquals(stringArray.length,languageList.size()); }


Happy Coding!

Topics:
java, tutorial, junit, array, list, java 8 stream, apache commons lang, commons collections, guava

Published at DZone with permission of John Thompson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

  • A Beginners Guide To Implementing MVVM Architecture In Flutter
  • Getting Started With Azure Load Testing
  • Understanding Eclipse's Plugin Build
  • Learn How to Use Vue and Spring Boot to Create a Single-Page App

Comments

Java Partner Resources