Sunday, 5 April 2020

How to copy elements of ArrayList to other list?

Approach 1: Pass the list as an argument to ArrayList constructor.
List<Integer> list2 = new ArrayList<>(list1);

Approach 2: Using addAll method of List.
List<Integer> list3 = new ArrayList<>();
list3.addAll(list1);

Approach 3: Using Collections.copy() method
List<Integer> list4 = new ArrayList<>();
list4.add(2);
list4.add(3);
list4.add(5);
list4.add(7);
Collections.copy(list4, list1);

Approach 4: Explicitly copying every element of the list.
List<Integer> list5 = new ArrayList<>();
for (int ele : list1) {
         list5.add(ele);
}

App.java
package com.sample.app;

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

public class App {

 private static void printListElements(List<Integer> list) {
  list.stream().forEach(ele -> {
   System.out.print(ele + " ");
  });
  System.out.println();
 }

 public static void main(String args[]) {
  List<Integer> list1 = Arrays.asList(1, 2, 3, 4);

  List<Integer> list2 = new ArrayList<>(list1);

  List<Integer> list3 = new ArrayList<>();
  list3.addAll(list1);

  List<Integer> list4 = new ArrayList<>();
  list4.add(2);
  list4.add(3);
  list4.add(5);
  list4.add(7);
  Collections.copy(list4, list1);

  List<Integer> list5 = new ArrayList<>();
  for (int ele : list1) {
   list5.add(ele);
  }

  printListElements(list1);
  printListElements(list2);
  printListElements(list3);
  printListElements(list4);
  printListElements(list5);

 }

}

Output
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4




You may like

No comments:

Post a Comment