How to convert an Array to a List in Java Program?

JavaObject Oriented ProgrammingProgramming

An array can be converted to a List easily using multiple ways.

Way #1

Create an empty list. Iterate through array and add each item to list using its add method.

for (int i = 0; i < array.length; i++) {
   list.add(array[i]);
}

Way #2

Use Arrays.asList() method to get a list from an array.

List<Integer> list = Arrays.asList(array);

Way #3

Use Collections.addAll() method to add elements of array to the list.

Collections.addAll(list, array);

Way #4

Use Streams to collect all elements of an array into the list.

List<Integer> list = Arrays.stream(array).collect(Collectors.toList());

Example

Following is the example showing the various methods to get a list from an array −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class CollectionsDemo {
   public static void main(String[] args) {
      Integer[] array = {1, 2, 3, 4, 5, 6};
      List<Integer> list = new ArrayList<>();
      for (int i = 0; i < array.length; i++) {
         list.add(array[i]);
      }
      System.out.println(list);
      List<Integer> list1 = Arrays.asList(array);
      System.out.println(list1);
      List<Integer> list2 = new ArrayList<>();
      Collections.addAll(list2, array);
      System.out.println(list2);
      List<Integer> list3 = Arrays.stream(array).collect(Collectors.toList());
      System.out.println(list3);
   }
}

Output

This will produce the following result −

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
raja
Updated on 10-May-2022 09:01:24

Advertisements