Java Program to copy value from one list to another list

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our array −

String[] str = { "P", "Q", "R", "S", "T", "U", "V", "W" };

Now set the elements of the above array to a new List −

int len = str.length;
List<String>list1 = new ArrayList<String>();
for (int i = 0; i < len; i++)
   list1.add(str[i]);

Consider a new List with no elements −

List<String>list2 = new ArrayList<String>();
for (int i = 0; i < len; i++)
   list2.add("");

Now copy value from one list to another −

Collections.copy(list2,list1);

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      String[] str = { "P", "Q", "R", "S", "T", "U", "V", "W" };
      int len = str.length;
      List<String>list1 = new ArrayList<String>();
      for (int i = 0; i < len; i++)
         list1.add(str[i]);
      List<String>list2 = new ArrayList<String>();
      for (int i = 0; i < len; i++)
         list2.add("");
      Collections.copy(list2,list1);
      ListIterator<String>iterator = list2.listIterator();
      System.out.println("New List...");
      while (iterator.hasNext())
         System.out.println(iterator.next());
   }
}

Output

New List...
P
Q
R
S
T
U
V
W
raja
Published on 24-Apr-2019 09:16:25
Advertisements