How to fill multiple copies of specified Object to a List in Java

Java 8Object Oriented ProgrammingProgramming

To fill multiple copies of specified object to a list means let’s say you have an element 100 and want to display it 10 times. For this, let us see an example.

The following is our list and iterator. We have used nCopiec Collections method to set the elements and how many copies you want −

List<Integer>list = Collections.nCopies(10, 100);
Iterator<Integer>iterator = list.iterator();

After that display the multiple copies −

while (iterator.hasNext())
System.out.println(iterator.next());

Example

 Live Demo

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<Integer>list = Collections.nCopies(10, 100);
      Iterator<Integer>iterator = list.iterator();
      System.out.println("Displaying 100 multiple times...");
      while (iterator.hasNext())
         System.out.println(iterator.next());
   }
}

Output

Displaying 100 multiple times...
100
100
100
100
100
100
100
100
100
100
raja
Published on 24-Apr-2019 15:01:37
Advertisements