Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Copy from List


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation,


How to copy one List to the other?


Example :



import java.util.ArrayList;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        List y = new ArrayList<>(x);

        for (String data : y) {
            System.out.println(data);
        }
    }
}		


Output :



  Mohan
  Kriti
  Salim

So, in the above code we have created a List,


List x = new ArrayList<>();

And initialised three names to the variable x,


x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Below is how the values are positioned in the List,

Spring_Boot

Then we have created a new List and passed the List x as parameter.


List y = new ArrayList<>(x);

And the new List y gets all the values of the List x.

Spring_Boot

And we get the below output,

Output :



  Mohan
  Kriti
  Salim

Note : The same code applies for LinkedList as well. Just that you need to replace ArrayList LinkedList.