Monday 27 April 2020

How to declare ArrayList with values?

Approach 1: Using Arrays.asList
List<Integer> list1 = Arrays.asList(2, 3, 5, 7);
                 
Approach 2: Using List.of (This is available in Java9 onwards)
List<Integer> list2 = List.of(2,  3, 5, 7);
                 
Approach 3: Using Stream.of()
List<Integer> list3 = Stream.of(2, 3, 5, 7).collect(Collectors.toList());
                 
Approach 4: Using ArrayList constructor.
List<Integer> list4 = new ArrayList<>(Arrays.asList(2, 3, 5, 7));

Find the below working application.

App.java
package com.sample.app;

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

public class App {

 public static void main(String args[]) {

  List<Integer> list1 = Arrays.asList(2, 3, 5, 7);

  List<Integer> list2 = List.of(2, 3, 5, 7);

  List<Integer> list3 = Stream.of(2, 3, 5, 7).collect(Collectors.toList());

  List<Integer> list4 = new ArrayList<>(Arrays.asList(2, 3, 5, 7));

  System.out.println("list1 : " + list1);
  System.out.println("list2 : " + list2);
  System.out.println("list3 : " + list3);
  System.out.println("list4 : " + list4);

 }

}

Output
list1 : [2, 3, 5, 7]
list2 : [2, 3, 5, 7]
list3 : [2, 3, 5, 7]
list4 : [2, 3, 5, 7]



You may like

No comments:

Post a Comment