Otavio Macedo Otavio Macedo - 5 months ago 12
Java Question

guava-libraries: List with n instances

The Java

Collections
class has the following method:

static <T> List<T> nCopies(int n, T o)


I need a similar method, but slightly more generic, which provides n instances of a given class. Something like:

static <T> List<T> nInstances(int n, Supplier<T> supplier)


In particular, if
supplier
is
Supplier.ofInstance(o)
, we get the same behavior as the
nCopies()
method. Is there such a method somewhere in the Guava API?

Thank you.

Answer

No, but it's easy enough to implement:

public static <T> List<T> nInstances(int n, Supplier<T> supplier){
    List<T> list = Lists.newArrayListWithCapacity(n);
    for(int i = 0; i < n; i++){
        list.add(supplier.get());
    }
    return list;
}
Comments