Create a new ArrayList from another collection in Java

Java 8Object Oriented ProgrammingProgramming

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);
raja
Published on 30-Jan-2019 10:49:49
Advertisements