Collections.nCopies() Method in java

The Java Collections.nCopies() method in java is used to return an immutable list which contains multiple copies of the same object.

This method is defined in the java.util.Collections class.

Syntax :- public static <T> List<T> nCopies(int n, T o)

 Here n : it is the number of copies return the list,

          o : The object to be repeated in the list.

  • Here we are creating immutable list less than 5 copies of the same string “welcome”.
  • Now analyze(List<String> data) method to check if data.size() > 5 then throw a ListToLargeException type.
  • Next If list size is not large, then print the list.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


class ListToLargeException extends RuntimeException {
	public ListToLargeException(String message) {
		super(message);
	}
}

public class DemoCopies {
	public void analyze(List<String> data) {
		if (data.size() > 5) {
			throw new ListToLargeException("list can not exceed more than 5");
		}
	}

	public static void main(String[] args) {
		DemoCopies demo = new DemoCopies();
		List<String> listData = new ArrayList<String>(Collections.nCopies(4, "welcome"));
		demo.analyze(listData);
		System.out.println("nCopies list returned is:- "+listData);
	}
}

Output :-
nCopies list returned is:- [welcome, welcome, welcome, welcome]