Create a new ArrayList from another collection in Java


An ArrayList can be created from another collection using the java.util.Arrays.asList() method. A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      String str[] = { "John", "Macy", "Peter", "Susan", "Lucy" };
      List aList = new ArrayList(Arrays.asList(str));
      System.out.println("The ArrayList elements are: " + aList);
   }
}

Output

The ArrayList elements are: [John, Macy, Peter, Susan, Lucy]

Now let us understand the above program.

The string array str[] is defined. Then an ArrayList is created using the Arrays.asList(). The ArrayList is displayed. A code snippet which demonstrates this is as follows −

String str[] = { "John", "Macy", "Peter", "Susan", "Lucy" };
List aList = new ArrayList(Arrays.asList(str));
System.out.println("The ArrayList elements are: " + aList);

Updated on: 30-Jul-2019

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements