VOOZH about

URL: https://dzone.com/articles/converting-between-java-list-and-array

⇱ How to Convert Between List and Array in Java


Related

  1. DZone
  2. Data Engineering
  3. Data
  4. 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 Aug. 01, 18 · Tutorial
Likes
Comment
Save
146.7K Views

Join the DZone community and get the full member experience.

Join For Free

It’s 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, I’ll discuss the various approaches to converting data between list objects and arrays.

Converting List to Array

The list interface comes with the toArray() 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 a list to 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 the convert()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 the convert() method of the ListToArrayConvertorclass 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 streamobject 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 listto 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 the List.toArray()method, you get wrapper arrays, such as  Integer[],  Double[],  andBoolean[]. 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 the Java 8 stream:

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


Another approach would be to convert a listto a primitive array by using the 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 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 an ArrayUtilsclass that is meant specifically to perform operations on arrays. Out of the several methods that ArrayUtilsprovides, 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 listto 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, and Booleans , with utility methods that are not already present in the standard Java wrapper classes. For example, the intsclass 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 listto 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 the Arrays.asList()method. This method returns a fixed-size list from the elements of the array passed to it.

An ArrayToListConverterclass that converts an array to a listcan 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 the  forCollectioninstances. You can use the addAll()method of CollectionUtils to convert an array to a list. 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 the CollectionUtilsclass 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 with Listobjects. You can use the newArrayList()method of the listsclass to convert an array to a  list. The  newArrayList()method takes an array and returns an ArrayList that has been initialized with the elements of the array.

The code to convert an array to a listusing the listsclass 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!

Data structure Convert (command) Java (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • Immutable Objects Using Record in Java
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: