Java Convert Array to ArrayList
By:Roy.LiuLast updated:2019-08-11
In Java, we can use new ArrayList<>(Arrays.asList(array)) to convert an Array into an ArrayList
ArrayExample1.java
package com.mkyong; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayExample1 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; List<String> list = new ArrayList<>(Arrays.asList(str)); list.add("D"); list.forEach(x -> System.out.println(x));
Output
The Arrays.asList returns a fixed or unmodifiable list, if we modify the list, UnsupportedOperationException will be thrown.
List<String> list = Arrays.asList(str); // unmodifiable list list.add("D"); // java.lang.UnsupportedOperationException List<String> list2 = new ArrayList<>(Arrays.asList(str)); // modifiable list list2.add("D"); // ok
1. Java 8 Stream
ArrayExample2.java
package com.mkyong; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArrayExample2 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; ArrayList<String> list1 = Stream.of(str).collect(Collectors.toCollection(ArrayList::new)); list1.add("D"); list1.forEach(x -> System.out.println(x)); List<String> list2 = Stream.of(str).collect(Collectors.toList()); list2.add("D"); list2.forEach(x -> System.out.println(x));
Output
2. Java 9 – List.of()
P.S List.of returns fixed or unmodifiable list
ArrayExample3.java
package com.mkyong; import java.util.ArrayList; import java.util.List; public class ArrayExample3 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; // Java 9 List<String> list = new ArrayList<>(List.of("A", "B", "C")); list.add("D"); list.forEach(x -> System.out.println(x));
Output
From:一号门
Previous:Java – Convert String to double
COMMENTS