Collections.nCopies in Java

By Arvind Rai, February 05, 2022
Find the Java doc of Collections.nCopies method.
static <T> List<T> nCopies(int n, T o) 
The nCopies method returns an immutable list consisting of n copies of the specified object.
n is the number of elements in the returned list.
o is the element that repeatedly added in the list.

Example-1

CollectionsNCopies1.java
package com.concretepage;
import java.util.Collections;
import java.util.List;

public class CollectionsNCopies1 {
  public static void main(String[] args) {
	List<String> list1 = Collections.nCopies(5, "Ram");
	System.out.println(list1);
	
	List<Integer> list2 = Collections.nCopies(10, 5);
	System.out.println(list2);	
  }
} 
Output
[Ram, Ram, Ram, Ram, Ram]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5] 

Example-2

package com.concretepage;
import java.util.Collections;
import java.util.List;

public class CollectionsNCopies2 {
  public static void main(String[] args) {
	Person p1 = new Person("A");
	List<Person> list = Collections.nCopies(20, p1);
	System.out.println(list.size()); // Output 20
  }
}
class Person {
  private String name;
  public Person(String name) {
	this.name = name;
  }
  public String getName() {
	return name;
  }
  public void setName(String name) {
	this.name = name;
  }
} 

Reference

Java Collections
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us