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
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024