- Как преобразовать List в Array и наоборот в Java
- Способ № 1 (JDK 11)
- Способ № 2 (JDK 8)
- Способ № 3 с использованием stream() (JDK 8)
- Метод для Generics
- Преобразование Array в List
- Исходный код
- Convert List to ArrayList in Java
- Converting List to ArrayList in Java
- Related Article — Java List
- Related Article — Java ArrayList
- How to get ArrayList to ArrayList and vice versa in java?
- Example
- Output
- Example
- Output
- can List convert to ArrayList ?
- How to Convert a Java Array to ArrayList
- Arrays.asList()
- new ArrayList<>(Arrays.asList())
- new ArrayList<>(List.of())
- Collections.addAll()
- Collectors.toList()
- Free eBook: Git Essentials
- Collectors.toCollection()
- Lists.newArrayList()
- Conclusion
Как преобразовать List в Array и наоборот в Java
Допустим, у нас есть список, и надо его преобразовать в массив. Как это сделать? Возьмем для примера список строк:
List list = new ArrayList<>(); list.add("Petya"); list.add("Vasya");
Мы хотим преобразовать его в массив:
Сделаем это без сторонних библиотек средствами JDK. Начнем с 11 версии, дальше покажу способы на 8 версии, и потом метод с Generics.
Способ № 1 (JDK 11)
Итак, с 11 версии список в массив можно преобразовать вот так изящно:
String[] stringArray = list.toArray(String[]::new);
Способ № 2 (JDK 8)
В 8 версии можно сделать так (внимание, в скобках параметром указываем тип массива, а иначе результирующий массив будет типа Object[]):
String[] stringArray = list.toArray(new String[0]);
Заметьте, что в аргументе можно указать массив нулевой длины, главное, что есть тип. В этом случае будет создан и вернется новый массив нужной длины. Если же список помещается, то вернется тот, что в аргументе.
Способ № 3 с использованием stream() (JDK 8)
String[] stringArray = list.stream().toArray(String[]::new);
Метод для Generics
Допустим, надо написать общий метод для любого типа данных:
private static String[] listToArray(List list)
Проверим, что он работает. Создадим класс:
class Person < private String name; public Person(String name) < this.name = name; >public String toString() < return name; >>
@Test public void m4() < Listlist=new ArrayList<>(); list.add(new Person("Petya")); list.add(new Person("Vasya")); String[] stringArray = listToArray(list); assertThat(stringArray[0], is("Petya")); assertThat(stringArray[1], is("Vasya")); >
Преобразование Array в List
Теперь допустим у нас есть массив строк:
String[] stringArray = new String[];
Массив в List преобразуется так:
List list = Arrays.asList(stringArray);
Но полученный массив — фиксированного размера, в него нельзя добавлять и удалять элементы. Менять же элементы внутри можно, при этом изменения отразятся на массиве. И наоборот.
Чтобы получить обычный List, можно создать новый List на основе предыдущего:
Исходный код
Код примеров доступен на GitHub (в тестах).
Convert List to ArrayList in Java
In this guide, we have talked about how you can convert a list to an ArrayList in Java. But before we go into it, you should be familiar with some of the basic concepts in Java. You need to understand that list is implemented by the Interface Collection , and ArrayList is an implemented class of List .
Converting List to ArrayList in Java
Let’s take a look at the example down below.
import java.util.*; public class Hello public static void main(String[] args) //Let's make a List first. ListString> MyList = (ListString>) Arrays.asList("Hello","World"); > >
The above List contains two string elements, as you can see. Here, Arrays.asList is a static method used to convert an array of objects into a List . Let’s see how we can have this List convert into an ArrayList .
Learn more about Array Class here.
import java.util.*; public class Hello public static void main(String[] args) //Let's make a List first. ListString> MyList = (ListString>) Arrays.asList("Hello","World"); ArrayListString> a1 = new ArrayListString>(MyList); > >
With this approach, we are actually initializing the ArrayList featuring its predefined values. We simply made a list with two elements using the Arrays.asList static method. Later we used the constructor of the ArrayList and instantiated it with predefined values. Learn more about ArrayList and its methods and other properties.
In other words, we had an array with elements in it and converted it into List and later turned that list into an ArrayList . Take a look at the example down below for understanding what’s happening.
import java.util.*; public class Hello public static void main(String[] args) String arr[]="1","2","3">; ListString> MyList = (ListString>) Arrays.asList(arr); //now we are converting list into arraylist ArrayListString> a1 = new ArrayListString>(MyList); for(int i=0; ia1.size(); i++) System.out.println(a1.get(i)); > > >
In the above program, we first made an Array with initializing values. Later, just like in the first example, instead of giving values, we passed an array, and we used Arrays.asList to convert this array of objects into a List .
The list that you get from Arrays.asList is not modifiable. It’s just a wrapper, and you can’t add or remove over it. Even if you try, you will get
UnsupportedOperationException
The problem here is to convert the list into an ArrayList , so we instantiated the ArrayList from the List . The output of the above program:
That’s how you convert the List into an ArrayList in Java.
Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.
Related Article — Java List
Related Article — Java ArrayList
Copyright © 2023. All right reserved
How to get ArrayList to ArrayList and vice versa in java?
Instead of the typed parameter in generics (T) you can also use “?”, representing an unknown type. These are known as wild cards you can use a wild card as − Type of parameter or, a Field or, a Local field. Using wild cards, you can convert ArrayList to ArrayList as −
ArrayList stringList = (ArrayList)(ArrayList)(list);
Example
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class ArrayListExample < public static void main(String args[]) < //Instantiating an ArrayList object ArrayListlist = new ArrayList(); //populating the ArrayList list.add("apples"); list.add("mangoes"); list.add("oranges"); //Converting the Array list of object type into String type ArrayList stringList = (ArrayList)(ArrayList)(list); //listing the contenmts of the obtained list Iterator it = stringList.iterator(); while(it.hasNext()) < System.out.println(it.next()); >> >
Output
ArrayList to ArrayList
To convert the ArrayList to ArrayList −
- Create/Get an ArrayList object of String type.
- Create a new ArrayList object of Object type by passing the above obtained/created object as a parameter to its constructor.
Example
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class ArrayListExample < public static void main(String args[]) < //Instantiating an ArrayList object ArrayListstringList = new ArrayList(); //populating the ArrayList stringList.add("apples"); stringList.add("mangoes"); stringList.add("oranges"); //Converting the Array list of String type to object type ArrayList objectList = new ArrayList(stringList); //listing the contents of the obtained list Iterator it = stringList.iterator(); while(it.hasNext()) < System.out.println(it.next()); >> >
Output
can List convert to ArrayList ?
posted 17 years ago
hi, i have use List list = new ArrayList to save objects, but somehow , some developer have method like this
is it possible i can convert List to ArrayList, then i passs it into method like above mentioned ?
author and iconoclast
posted 17 years ago
If you have a List that’s really an ArrayList, then you can use a cast:
List myList = .
methodName((ArrayList) myList);
But if it’s not, or if you’re not sure, then just construct a new ArrayList using the contents of the first list:
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 :
Employee emp1 = new Employee("John"); Employee emp2 = new Employee("Sarah"); Employee emp3 = new Employee("Lily"); Employee[] array = new Employee[]; List list = Arrays.asList(array); System.out.println(list);
This will result in a List implementation ( ArrayList ) to be populated with emp1 , emp2 and emp3 . Running this code results in:
[Employee, Employee, Employee]
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:
Employee[] array = new Employee[]; List list = new ArrayList<>(Arrays.asList(array)); System.out.println(list);
[Employee, Employee, Employee]
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:
List list = new ArrayList<>(List.of(emp1, emp2, emp3)); System.out.println(list);
[Employee, Employee, Employee]
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:
Employee[] array = new Employee[]; List list = new ArrayList<>(); Collections.addAll(list, array); System.out.println(list);
[Employee, Employee, Employee]
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() :
Employee[] array = new Employee[]; List list = Stream.of(array).collect(Collectors.toList()); System.out.println(list);
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!
[Employee, Employee, Employee]
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:
Employee[] array = new Employee[]; List list = Stream.of(array) .collect(Collectors.toCollection(ArrayList::new)); System.out.println(list);
[Employee, Employee, Employee]
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:
Employee[] array = new Employee[]; List list = Lists.newArrayList(array);
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 > 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.