Converting to array

There are two methods that allow converting a list to an array:

Both methods preserve the order of the elements. Here is the demo code that shows how to do it:

List<String> list = new ArrayList<>();
list.add("s1");
list.add("s2");

Object[] arr1 = list.toArray();
for(Object o: arr1){
System.out.print(o); //prints: s1s2
}

String[] arr2 = list.toArray(new String[list.size()]);
for(String s: arr2){
System.out.print(s); //prints: s1s2
}

Yet, there is another way to convert a list or any collection for that matter to an array – using a stream and functional programming:

Object[] arr3 = list.stream().toArray();
for (Object o : arr3) {
System.out.print(o); //prints: s1s2
}

String[] arr4 = list.stream().toArray(String[]::new);
for (String s : arr4) {
System.out.print(s); //prints: s1s2
}

Streams and functional programming have made many traditional coding solutions obsolete. We will discuss this in Chapter 17, Lambda Expressions and Functional Programming and in Chapter 18, Streams and Pipeline.