JavaRush /Java Blog /Random EN /Java list to array: convert a list of elements into an ar...
Анзор Кармов
Level 31
Санкт-Петербург

Java list to array: convert a list of elements into an array

Published in the Random EN group
Hello! In this article, we will look at how to convert a list of elements into an array of elements in Java. Actually, there are not so many ways to do this, and they are all simple, so the article will not be complicated. Java list to array: convert a list of elements into an array - 1Let's immediately decide what we are working with. We will convert lists into arrays, and more specifically, a list of strings: I, love, learning, on, JavaRush will be converted into an array of the same strings. But first, a little bonus. Let's talk about how to quickly write down a list.

How to quickly write down a list to array

Remember: there are two scenarios in this life. The first is utter melancholy and boredom when we initialize a new list:
List<String> wordsList = new ArrayList();
And then we add values ​​to it... One by one...
wordsList.add("I");
wordsList.add("love");
wordsList.add("learning");
wordsList.add("on");
wordsList.add("JavaRush");
No good. I forgot why the list was needed while I was creating it! The second way is to cut off all unnecessary things and adopt... utility classes. For example, the class Arrays, which has an incredibly convenient method asList. You can pass into it whatever you want to make a list, and the method will make it a list. Something like this:
List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");
This method takes into itself varargs- in a sense, an array. I apologize for the fact that in the lecture called list to array I taught you array to list first, but circumstances required it. Well, now to our methods for converting lists into arrays.

Method No. 1. Bust

This method is perfect for those who like to type code on the keyboard without much thought. A kind of meditation. Step 1. Create an array of the same length as the list:
List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");
String[] wordsArray = new String[wordsList.size()];
Step 2. Create a loop with a counter to iterate through all the elements of the list and be able to access the array cells by index:
for (int i = 0; i < wordsList.size(); i++) {

}
Step 3. Inside the loop, we assign the value of each list element with index i to the array cell with index i:
for (int i = 0; i < wordsList.size(); i++) {
    wordsArray[i] = wordsList.get(i);
}
Result:
public static void main(String[] args) {

        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");
        String[] wordsArray = new String[wordsList.size()];

        for (int i = 0; i < wordsList.size(); i++) {
            wordsArray[i] = wordsList.get(i);
        }
    }

Method No. 2. toArray method

Probably the most optimal thing to use. The interface Listhas two methods toArraythat create an array from the current list:
Object[] toArray();
 T[] toArray(T[] a);
The first method returns an array of objects containing all the elements of the current list (from first to last):
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");
        String[] wordsArray = (String[]) wordsList.toArray();

        for (String word : wordsArray) {
            System.out.println(word);
        }

    }
}
Let's run the method mainand see the following:

I
love
learning
on
JavaRush
However, this method has a peculiarity: it always returns an array of objects (Object[]). Therefore, the returned result must be cast to the desired data type. In the example above we cast it to an array of strings (String[]). But this method does not accept arguments, which can be convenient in some situations. The second method also returns an array containing all the elements of the current list (from first to last). However, unlike the first, the second method takes an array of a certain type as an argument. But the result of the second method will not be an array of objects, but an array of a certain data type - the same as the data type in the array method passed as arguments.
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");
        String[] wordsArray = wordsList.toArray(new String[0]);

        for (String word : wordsArray) {
            System.out.println(word);
        }

    }
}
If we run the method main, we will see the same words in the output:

I
love
learning
on
JavaRush
Let's talk a little about the array that is passed as an argument to the toArray. The logic of the method depends on the length of the transmitted array. There are three possible scenarios:

1. The length of the transmitted array is less than the length of the list

In this case, the method creates a new array and places the list elements into it. We demonstrated this in the example above.

2. The length of the element being passed is equal to the length of the list

The method will place the list elements into the passed array. Let's demonstrate this:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");

        // Создаем пустой массив нужной длины
        String[] array = new String[wordsList.size()];

        // Отправляем пустой массив в метод toArray
        wordsList.toArray(array);

        // Проверяем, заполнился ли наш массив. Спойлер: да
        for (String word : array) {
            System.out.println(word);
        }

    }
}
When outputting, we will see all the same lines, and it will become clear that the method has filled the array we created.

3. The length of the transmitted array is greater than the length of the list

The method will write all the elements of the list into an array, and will write the value into the cell next to the last added element null. Let's demonstrate this:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");

        // Создаем пустой массив, длина которого в 2 раза больше длины списка
        String[] array = new String[wordsList.size() * 2];

        for (int i = 0; i < array.length; i++) {
            // В каждую ячейку запишем строковое представление текущего индекса
            array[i] = String.valueOf(i);
        }

        // Отправляем массив в метод toArray
        wordsList.toArray(array);

        // Проверяем, что лежит в нашем массиве
        for (String word : array) {
            System.out.println(word);
        }

    }
}
After running the method mainin the console we will see the following:

I
love
learning
on
JavaRush
null
6
7
8
9
Which method out of the three should you choose? In early versions of Java, it was optimal to pass an array with a length equal to or greater than the length of the list. However, modern JVMs have optimizations, and in some cases they provide faster performance for a method that is passed an array of shorter length than the length of the list. So if you're running a modern version of Java, pass an empty array to the method like we did in the first example:
wordsList.toArray(new String[0]);

Method number 3. Stream API

This method is suitable for those who want to not only convert a list into an array, but also solve a couple of other problems along the way. And also for people familiar with the Java Stream API. JavaRush has a good article on this topic . In this section we will look at several examples using streams. How to convert a list to an array using streams:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");

        String[] strings = wordsList.stream()
                .toArray(String[]::new);

        for (String s : strings) {
            System.out.println(s);
        }

        /*
        Output:
        I
        love
        learning
        on
        JavaRush

         */
    }
}
But if you just need to cast a list to an array, then it is better to do this using the method toArraydescribed in Method No. 2. But if you want not only to convert a list to an array, but also to perform some action on each element, then this is the right place for you. Let's try to convert the list to an array so that in the final array all lines are written in uppercase:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");

        String[] strings = wordsList.stream()
                .map(str -> str.toUpperCase())
                .toArray(String[]::new);

        for (String s : strings) {
            System.out.println(s);
        }

        /*
            Output:
            I
            LOVE
            LEARNING
            ON
            JAVARUSH

         */
    }
}
Here in .map(str -> str.toUpperCase())we have defined what needs to be done with each line in the list. In this case, we decided to convert each string to upper case and then collect it into an array. Using the Stream API allows you to not only transform each value, but also filter them. Suppose we want to collect an array from a list of strings, but in such a way that only strings longer than two characters are included in the array:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "JavaRush");

        String[] strings = wordsList.stream()
                .filter(str -> str.length() > 2)
                .map(str -> str.toUpperCase())
                .toArray(String[]::new);

        for (String s : strings) {
            System.out.println(s);
        }

        /*
            Output:
            LOVE
            LEARNING
            JAVARUSH
         */
    }
}
Here in the line .filter(str -> str.length() > 2)we have created a so-called filter that will be applied to each element of the list before it gets into the array. In this case, the method is called for each row length(), and if the result of the expression str.length() > 2is true, such a row will end up in the resulting selection, and ultimately in the array. Otherwise, it won't hit. Here, perhaps, it is worth saying that the same can be achieved by simply iterating over the elements and imposing various restrictions. You can do it this way too. Stream API provides a more functional approach to solve such problems.

Results

In this article, we looked at various ways to convert lists to arrays:
  • simple search;
  • methodtoArray;
  • Stream API.
The best option is to use the method toArraythat is defined in the interface List. There are two such methods:
  • Object[] toArray();
  • T[] toArray(T[] a);
The first one does not accept arguments, but returns an array of objects, which is why you will most often have to resort to explicit type casting. The second returns an array of the desired type, but takes an array as an argument. It is best to pass an empty array to the method, and you will be happy. Using the Stream API allows you not only to convert a list to an array, but also to perform some actions along the way, such as filtering or converting elements before adding them to the array.

Homework

Try to repeat all the examples from this article yourself, but instead of the original list of strings, use a list of integers from 0 to 10. Naturally, you will have to adapt some conditions from the examples that apply only to strings to the new conditions.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION