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


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements