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

Java list to array: convert list of elements to 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 be simple. Java list to array: convert list of elements to array - 1Let's get straight to the point of what we're working on. We will convert lists into arrays, and more specifically, a list of strings: I, love, learning, on, CodeGym will be converted into an array of the same strings. But first, a small bonus. Let's talk about how to quickly file a list.

How to quickly file a list to array

Remember: there are two scenarios in this life. The first is sheer boredom when we initialize a new list:
List<String> wordsList = new ArrayList();
And then we add values ​​​​to it ... One at a time ...
wordsList.add("I");
wordsList.add("love");
wordsList.add("learning");
wordsList.add("on");
wordsList.add("CodeGym");
Doesn't fit anywhere. I already forgot why the list was needed while creating it! The second way is cutting off everything superfluous and adopting ... utility classes. For example, a class Arraysthat has an incredibly convenient asList. You can pass whatever you want to be a list to it, and the method will make it a list. Like this:
List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "CodeGym");
This method accepts varargs- in a sense, an array. I'm sorry that in a lecture called list to array, I taught you array to list first, but the circumstances required it. Well, now to our methods for converting lists to arrays.

Method number 1. Bust

The method is perfect for those who like to type code on the keyboard without being particularly thoughtful. 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", "CodeGym");
String[] wordsArray = new String[wordsList.size()];
Step 2. We create a loop with a counter to run through all the elements of the list and be able to access the cells of the array by index:
for (int i = 0; i < wordsList.size(); i++) {

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

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

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

Method number 2. toArray method

Probably the best 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 that contains 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", "CodeGym");
        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
CodeGym
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 take arguments, which in some situations can be convenient. The second method also returns an array containing all the elements of the current list (from first to last). However, unlike the first method, 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 in the arguments.
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "CodeGym");
        String[] wordsArray = wordsList.toArray(new String[0]);

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

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

I
love
learning
on
CodeGym
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 passed array. There are three possible scenarios:

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

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

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

The method will put the elements of the list 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", "CodeGym");

        // Создаем пустой массив нужной длины
        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 filled the array we created.

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

The method will write all the elements of the list to an array, and will write the value to the cell following 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", "CodeGym");

        // Создаем пустой массив, длина которого в 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
CodeGym
null
6
7
8
9
Which of the three methods to 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, there are optimizations in modern JVMs, and in some cases they make a method that is passed an array smaller than the length of the list faster. So if you're running a modern version of Java, pass an empty array to the method, as 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 the list into an array, but also solve a couple of other tasks along the way. And also - to people familiar with the Java Stream API. CodeGym has a good article on this subject . In this section, we will look at several examples using streams. How to cast 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", "CodeGym");

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

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

        /*
        Output:
        I
        love
        learning
        on
        CodeGym

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

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

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

        /*
            Output:
            I
            LOVE
            LEARNING
            ON
            CODEGYM

         */
    }
}
Here in .map(str -> str.toUpperCase())we have defined what needs to be done with each row in the list. In this case, we decided to convert each string to uppercase and then collect it into an array. Using the Stream API allows you not only to transform each value, but also to 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 get into the array:
public class Main {
    public static void main(String[] args) {
        List<String> wordsList = Arrays.asList("I", "love", "learning", "on", "CodeGym");

        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
            CODEGYM
         */
    }
}
Here in line, .filter(str -> str.length() > 2)we have created what is called a 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 be included in the resulting selection, and eventually in the array. Otherwise, it won't hit. Here, perhaps, it is worth saying that the same can be achieved simply by iterating over the elements and imposing various restrictions. You can do that too. The Stream API provides a more functional approach for solving such problems.

Results

In this article, we looked at various ways to cast lists to arrays:
  • simple enumeration;
  • 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 takes no arguments, but returns an array of objects, which is why you will most often have to resort to explicit type casting. The second one returns an array of the desired type, but takes an array as an argument. It's best to pass an empty array to the method and you'll be fine. Using the Stream API allows you not only to cast the 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.Java list to array: convert list of elements to array - Stack Overflow

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 of the 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