- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements