Как преобразовать массив в arraylist java

от admin

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Как преобразовать массив Java в ArrayList

Введение В этом руководстве мы конвертируем массив в более универсальный ArrayList в Java. * Arrays.asList () * new ArrayList <> (Arrays.asList ()) (Самый популярный и используемый подход) * new ArrayList <> (List.of ()) * Collections.addAll () * Collectors.toList () * Collectors.toCollection () * Lists.newArrayList () Массивы просты и обеспечивают базовую функциональность группирования вместе коллекции объектов или примитивных типов данных. Однако и массивы ограничены — их размер фиксированный.

Время чтения: 3 мин.

Вступление

В этом руководстве мы конвертируем массив в более универсальный ArrayList в Java.

Массивы просты и обеспечивают базовую функциональность по группированию коллекции объектов или примитивных типов данных. Однако массивы также ограничены — их размер фиксирован, и даже основные операции, такие как добавление новых элементов в начале или перестановка элементов, могут быть сложными.

К счастью, Collections Framework познакомила нас со многими очень полезными реализациями List , Set и Queue .

Одним из них является ArrayList , действительно универсальная и популярная реализация List .

ArrayList примет любую Collection . Мы можем проявить творческий подход к типу коллекции, которую передаем в нее.

Arrays.asList ()

Начнем с простейшей формы преобразования. У Arrays есть много полезных методов. Метод asList() возвращает содержимое массива в List :

Это приведет к List реализации ( ArrayList ) , который будет населен emp1 , emp2 и emp3 . Выполнение этого кода приводит к:

новый ArrayList <> (Arrays.asList ())

Лучшим подходом, чем просто присвоение возвращаемого значения вспомогательного метода, является передача возвращаемого значения в new ArrayList<>() . Это стандартный подход, используемый большинством людей.

Это потому, что метод asList() поддерживается исходным массивом.

Если вы измените исходный массив , список также изменится. Кроме того, asList() возвращает фиксированный размер, поскольку он поддерживается фиксированным массивом. Операции, которые расширяют или сокращают список, возвращают UnsupportedOperationException .

Чтобы избежать этого, мы применим функции ArrayList , передав возвращаемое значение asList() конструктору:

новый ArrayList <> (List.of ())

Начиная с Java 9, вы можете пропустить инициализацию самого массива и передать его конструктору. Вы можете использовать List.of() и передавать отдельные элементы:

Collections.addAll ()

Класс Collections предлагает множество полезных вспомогательных методов, среди которых есть метод addAll() . Он принимает Collection и набор elements и объединяет их.

Он очень универсален и может использоваться со многими ароматами коллекции / vararg. Мы используем ArrayList и массив:

Collectors.toList ()

Если вы работаете с потоками, а не с обычными коллекциями, вы можете собрать элементы потока и упаковать их в список с помощью toList() :

Выполнение этого даст:

Collectors.toCollection ()

Точно так же вы можете использовать метод toCollection() для сбора потоков в разные коллекции. В нашем случае мы предоставим в него ссылку ArrayList::new , хотя вы также можете указать другие ссылки:

Это также приводит к:

Lists.newArrayList ()

Подобно вспомогательному классу и методу Arrays.asList() , проект Google Guava познакомил нас с вспомогательным классом Lists Вспомогательный класс Lists newArrayList() :

Теперь ключевым выводом этого подхода было то, что вам не нужно указывать тип при инициализации ArrayList . Это было действительно полезно, когда у вас был список <Element <Element, Element>> .

Однако, поскольку Java 7 устранила необходимость явно указывать тип в операторе ромба, это стало устаревшим.

Заключение

Существует множество способов преобразовать массив в ArrayList в Java. Они охватывают от вызова вспомогательных методов до потоковой передачи массива и сбора элементов.

How to Convert a Java Array to ArrayList

In this tutorial, we'll be converting an array into a more versatile ArrayList in Java.

Arrays are simple and provide the basic functionality of grouping together a collection of objects or primitive data types. However, arrays are also limited — their size is fixed and even basic operations like adding new items at the beginning or rearranging elements can get complicated.

Thankfully, the Collections Framework introduced us to many very useful implementations of List s, Set s, and Queue s.

One of these is the ArrayList , a really versatile and popular implementation of a List .

An ArrayList 's constructor will accept any Collection . We can get creative with the type of collection we pass into it.

Arrays.asList()

Let's start off with the simplest form of conversion. The Arrays helper class has a lot of useful methods. The asList() method returns the contents of the array in a List :

This will result in a List implementation ( ArrayList ) to be populated with emp1 , emp2 and emp3 . Running this code results in:

new ArrayList<>(Arrays.asList())

A better approach than just assigning the return value of the helper method is to pass the return value into a new ArrayList<>() . This is the standard approach used by most people.

This is because the asList() method is backed by the original array.

If you change the original array, the list will change as well. Also, asList() returns a fixed size, since it's backed by the fixed array. Operations that would expand or shrink the list would return a UnsupportedOperationException .

To avoid these, we'll apply the features of an ArrayList by passing the returned value of asList() to the constructor:

Читать:
Как остановить программу в матлаб

This results in:

new ArrayList<>(List.of())

Since Java 9, you can skip initializing an array itself and passing it down into the constructor. You can use List.of() and pass individual elements:

This results in:

Collections.addAll()

The Collections class offers a myriad of useful helper methods and amongst them is the addAll() method. It accepts a Collection and a vararg of elements and joins them up.

It's very versatile and can be used with many collection/vararg flavors. We're using an ArrayList and an array:

This results in:

Collectors.toList()

If you're working with streams, rather than regular collections, you can collect the elements of the stream and pack them into a list via toList() :

Running this will yield:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Collectors.toCollection()

Similarly, you can use the toCollection() method to collect streams into different collections. In our case, we'll supply the ArrayList::new method reference into it, though you could supply other references as well:

This also results in:

Lists.newArrayList()

Similar to the Arrays.asList() helper class and method, Google's Guava project introduced us to the Lists helper class. The Lists helper class provides the newArrayList() method:

Now, the key takeaway of this approach was that you don't need to specify the type when initializing an ArrayList . This was really useful when you'd have a <Element <Element, Element>> list.

However, as Java 7 removed the need to explicitly set the type in the diamond operator, this became obsolete.

Conclusion

There are numerous ways to convert an array to an ArrayList in Java. These span from calling helper methods to streaming the array and collecting the elements.

Преобразование массива в список в Java

В этом посте будет обсуждаться, как преобразовать массив в список, используя простые коллекции Java, Guava и Apache Commons.

В Java есть две реализации списков общего назначения: ArrayList а также LinkedList . Этот пост будет использовать ArrayList , который предлагает постоянный позиционный доступ и просто быстрый.

1. Наивное решение

Наивное решение состоит в том, чтобы создать пустой список и поместить в него каждый элемент указанного массива.

Create ArrayList From Array in Java

Create ArrayList From Array in Java

This tutorial article will introduce different ways to create ArrayList from array in Java. There are three different methods to convert an array to ArrayList in Java such as Arrays.asList() , Collections.addAll() and add() .

Before proceeding with the demonstration, let us understand what is an array and ArrayList and how they differ from each other.

What Is an Array in Java?

An array is a collection of a fixed number of similar types of data. For example, if we want to store the data of 50 books, we can create an array of the string type that can hold 50 books. After creation, the length of the array is fixed. An array is the basic built-in functionality of Java.

What Is ArrayList in Java?

The ArrayList is a resizable array that stores a dynamic collection of elements found within the java.util package.

Difference Between Array and ArrayList in Java

The main difference between an array and ArrayList is that the length of an array cannot be modified or extended. To add or remove elements to/from an array, we have to create a new list. Whereas, elements can be added or removed to/from ArrayList at any point due to its resizable nature.

Conversion of an Array to ArrayList Using Arrays.asList()

Using Arrays.asList() , the array is passed to this method and a list object is obtained, which is again passed to the constructor of the ArrayList class as a parameter. The syntax of the Arrays.asList() is as below:

Let us follow the below example.

Conversion of an Array to ArrayList Using Collections.addAll()

This method lists all the array elements in a definite collection almost similar to Arrays.asList() . However, Collections.addAll() is much faster as compared to Arrays.asList() method on performance basis. The syntax of Collections.addAll() is as below:

Let us understand the below example.

Conversion of an Array to ArrayList Using add()

Using this method, we can create a new list and add the list elements in a much simpler way. The syntax for the add() method is as below:

Let us check the below example.

Following the above methods, we can now easily convert an array to ArrayList .

Похожие статьи