- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an Array to a List in Java Program?
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]
Advertisements