Conversion Between Array and List in Java

In this short article, we will write a Java program to convert Array to List and vice versa.

Convert Array to List

Let's write a Java program to convert Array to List:
package net.javaguides.hibernate;

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

public class ConvertArrayToListExample {
 public static void main(String[] args) {
  
  List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
  
  // convert List to array
  Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);

  // print set
  System.out.println(Arrays.toString(targetArray));
 }
}
Output:
[0, 1, 2, 3, 4, 5]

Convert List to Array

Let's write a Java program to convert List to Array:
package net.javaguides.hibernate;

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

public class ConvertArrayToListExample {
    public static void main(String[] args) {
        Integer[] sourceArray = {
            0,
            1,
            2,
            3,
            4,
            5
        };

        // convert array to list
        List < Integer > targetList = Arrays.asList(sourceArray);
        // print list
        targetList.forEach(value - > System.out.println(value));
    }
}
Output:
0
1
2
3
4
5

Similar Collections Examples [Snippet]


Comments