Java – Convert Array to ArrayList

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


A
B
C
D

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


A
B
C
D
A
B
C
D

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


A
B
C
D

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar