Skip to content

Different ways of converting Array to ArrayList() in Java

In this post, we are going to see different ways of converting Array to ArrayList() in Java.

  • Arrays.asList() method of java.util.Arrays class. Used to return a fixed-size list backed by the specified array. List is serializable and allows random access.
  • Collections.addAll() method add all the element to the specified array. It is faster in performance. So this is a best way to get the array converted to ArrayList.
  • Iteration – An traditional method to add all the arrays manually.

To know the difference between the Array and ArrayList() see our another post: Array vs ArrayList in Java

Example

package MyFunctions;

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

public class ArrayToArrayList {
	
	public static void main(String args[]) {
	      String[] array = {"Apple", "Banana", "Kiwi", "Dates", "Grapes"};

	      //Method 1
	      List<String> list = Arrays.asList(array);          
	      System.out.println(list);

	      //Method 2
	      List<String> list1 = new ArrayList<String>();
	      Collections.addAll(list1, array);
	      System.out.println(list1);

	      //Method 3
	      List<String> list2 = new ArrayList<String>();
	      for(String text:array) {
	         list2.add(text);
	      }
	      System.out.println(list2);
	   }  

}

Output

[Apple, Banana, Kiwi, Dates, Grapes]
[Apple, Banana, Kiwi, Dates, Grapes]
[Apple, Banana, Kiwi, Dates, Grapes]

Happy Learning 🙂

See also  Converting ArrayList to Array and Array to ArrayList in Java
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.