2018/02/15

Convert between arrays and lists with streams with Java

There are several ways of converting between arrays and lists but there are some gotchas when converting with non-streams methods. In reality, this kind of conversion should not happen that often (this could be an indicator of a bad/immature interface).
I barely remember all these methods and an extra reason if because of the lack of API asymmetry or consistency in Java constructors/factory methods.
For example, since there is Arrays.asList(...) I would expect Lists.asArray(...) but No!. There is mylist.toArray()!?.
The same problem is not gone when using streams but at least the result array/list does not have the pitfalls non-stream approaches have.

To me, it looks like using Streams is the easiest way of doing this kind of tasks since Java 8 is quite common nowadays :)

These are the packages I would be using...
import java.util.*;
import java.util.Arrays;

Creating arrays

Create array of ints (literal)
int[] array = {7, 8, 9};
Create array of ints (non literal ?)
int[] array = new int[3];
array[0] = 7;
array[0] = 8;
array[0] = 9;
Pretty print array:
String pretty = Arrays.toString(array);
System.out.println(pretty);

Creating lists

Create list of ints. Since List can hold only objects primitives must be boxed. In this case they are boxed into Integer.
List<Integer> list = new ArrayList<>();
list.append(7);
list.append(8);
list.append(9);
Pretty print list.

No direct method, we must convert to array first. See below.

Converting array to list

The usual method is Array.asList(...) however there is a catch: the array must contain objects, otherwise it will create a list with a single object.
// Objects:
String[] objectArray = {"A", "B", "C"};
List<String> objectList = new ArrayList(Arrays.asList(objectArray));
One way to convert primitive array to List would be using Streams (Nowadays I hope you are already using at least Java 8 :p):
import java.util.stream.Collectors;
import java.util.stream.Stream;
// Primitives
int[] array = new int[] {7,8,9};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList()); // 🤗
Also we can convert arrays of objects to lists in the same manner with streams:
// Objects
String[] objectArray = {"A", "B", "C"};
List<String> objectList = Arrays.stream(objectArray).collect(Collectors.toList()); // 🤗

Converting list to array

List<Integer> list = new ArrayList<>();
//Integer[] array = list.toArray(); // Be careful to not to do this! Check https://stackoverflow.com/a/13647072/149008
Integer[] array = list.toArray(new String[0]);
Another way is to use streams. Which is nicer because we get unboxed ints :)
List<Integer> list = new ArrayList<>();
list.add(7);
list.add(8);
list.add(9);
int[] array = list.stream().mapToInt(Integer::intValue).toArray();  // 🤗
Also we can use streams to convert Object list to Object array
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
//String[] array = (String [])list3.stream().map(i -> i).toArray(); // Be careful to not to do this
String[] array = list.stream().toArray(String[]::new);  // 🤗
Useful Link: Java Array to List Examples

0 comments :