In this short article, we are going to explore different ways of converting a list to array in Java.

First, we’ll start by taking a look at the basic approach. Then we’ll dig deeper to see how to achieve the same thing in a more succinct way using Java 8.

Finally, we are going to showcase how to use Guava and Apache Commons libraries to perform the conversion.

Java List to Array

Converting a List into an array can be very handy when we are invoking a third-party method returning a list inside a method that returns an array.

So, let’s see how we can achieve this in Java.

Feel free to check our articles about array conversion in Java:

Using Plain Java

The most basic way to convert a List of objects to an array in Java is to use a loop.

We can iterate over the list and push each element into our array:

    
        public class ListToArrayExample {
            public ListToArrayExample() { 
            }
            public static void  main(String[] args) {
                // create a List of string
                List<String> namesList = new ArrayList<String>();
                namesList.add("Linda");
                namesList.add("John");
                namesList.add("Karin"); 
                namesList.add("Azhwani"); 
                namesList.add("Isabella");
                namesList.add("Lucas");
                // Using iterator interface
                String namesArray[] = new String[namesList.size()];
                Iterator<String> namesIterator = namesList.iterator();
                int index = 0;
                while (namesIterator.hasNext()) {
                    namesArray[index] = namesIterator.next();
                    index++;
                }
                for (String stri : namesArray) {
                    System.out.println(stri);
                }
                // Using For loop
                String namesArray2[] = new String[namesList.size()];
                for (int i = 0; i < namesList.size(); i++) {
                    namesArray2[i] = namesList.get(i);
                }
                for (String stri : namesArray2) {
                    System.out.println(stri);
                }
            }
        }
    

Using toArray() Method

toArray() method is defined in the List interface. It returns a simple array containing all of the elements of the given list.

This handy method provides the easiest way to accomplish list array conversion in Java.

Let’s see together how we can use toArray() to convert a collection of String objects into an array:

    
        public class ToArrayExample {
            public ToArrayExample() { 
            }
            public static void  main(String[] args) {
                List<String> days = new ArrayList<String>();
                days.add("Monday");
                days.add("Thursday");
                days.add("Sunday"); 
                // toArray copies the list elements into the passed array
                String daysArray[] = new String[days.size()];
                daysArray = days.toArray(daysArray);
                for (String day : daysArray) {
                    System.out.println("Day = " + day);
                }
            }
        }
    

Using Java 8 Stream.toArray()

Stream API comes with a handy method called Stream.toArray(). We can use this method to return an array containing the elements of a particular list.

This below example illustrates how to convert a list to an array with the help of the Stream.toArray() method:

    
        import java.util.ArrayList;
        import java.util.stream.Stream;
        public class StreamToArrayExample {
            public StreamToArrayExample() { 
            }
            public static void  main(String[] args) {
                List<String> months = new ArrayList<String>();
                months.add("January");
                months.add("February");
                months.add("April"); 
                months.add("August"); 
                // Create a Stream from our List
                Stream<String> monthsStream = months.stream();
                // Convert the stream into an array of Strings
                String[] monthsArr = monthsStream.toArray(String[]::new);
                for (String month : monthsArr) {
                    System.out.println("Month = " + month);
                }
            }
        }
    

Using Guava

Now, let’s see how we can use the Guava API to perform the conversion. First thing first, we need to add the Guava dependency in the pom.xml:

    
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
    

Guava comes with a set of utility classes such as Ints, Longs, and Doubles. Each class provides a convenient method called toArray() for converting a list to a primitive array.

The following example showcases how to use Doubles.toArray() to convert a list of Double to an array:

    
        public class ListToArrayUsingGuava {
            public ListToArrayUsingGuava() { 
            }
            public static void main(String[] args) {
                List<Double> myList = Arrays.asList(1.56, 6.86, 56.3, 34.67);
                double[] myArray = Doubles.toArray(myList);
                System.out.println(Arrays.toString(myArray));
            }
        }
    

Please bear in mind that the Guava’s toArray() methods will throw a NullPointerException if the specified list or any of its elements is null.

So, to avoid the NPE exception, we need to make sure that the passed list does not hold any null value.

Using Apache Commons Lang

Apache Commons Lang is another great library that provides a host of helper classes. Among these utilities, there is the ArrayUtils class.

ArrayUtils comes with a set of handy methods for performing operations on arrays. For example, it provides the toPrimitives() method to convert an array of wrapper objects to primitives.

Now, let’s see how we can use Apache Commons Lang to convert a list to array:

    
        public class ConvertWithApacheCommonsLang {
            public ConvertWithApacheCommonsLang() { 
            }
            public static void main(String[] args) {
                List<Integer> myList = Arrays.asList(10, 6, 12, 90, 34);
                int[] myArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));
                System.out.println(Arrays.toString(myArray));
            }
        }
    

Handle null Values When Converting List to Array

Handling null values is an important thing to keep in mind, especially when we are converting a List to a primitive array.

As we have mentioned earlier, trying to convert a list that contains a null value may lead to NullPointerException.

So to avoid this scenario, we can use Java 8 to filter on null values:

    
        List<Integer> myList = Arrays.asList(7, 62, 59, null, 39, 44);
        int[] myArray = Ints.toArray(myList.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList()));
    

Conclusion

To sum it up, the native approach is generally enough to convert a list to array in Java.

However, for more advanced ways, we can use Java 8 Stream API or the clean and flexible Guava API.