How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provide a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.List;

public class ArraysExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2006"};
        List<String> list = Arrays.asList(words);

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

The results of our code are:

Happy
New
Year
2006

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia 🇮🇩. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply