Convert Array to List in Java

In this short article, we will write a Java program to convert Array to List and vice versa.
Learn and master Java Collections Framework at Learn Java Collections Framework

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]

Learn and master Java Collections Framework at Learn Java Collections Framework

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments