How do I convert a collection object into an array?

To convert collection-based object into an array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java.util.ArrayList.

package org.kodejava.util;

import java.util.List;
import java.util.ArrayList;

public class CollectionToArrayExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Kode");
        words.add("Java");
        words.add("-");
        words.add("Learn");
        words.add("Java");
        words.add("by");
        words.add("Examples");

        String[] array = words.toArray(new String[0]);
        for (String word : array) {
            System.out.println(word);
        }
    }
}

Our code snippet result is shown below:

Kode
Java
-
Learn
Java
by
Examples
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.