Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 607
Otavio Macedo Avatar asked Jan 20 '23 21:01

Otavio Macedo


1 Answers

No there isn't, and any equivalent construct (that just stores the int n and the supplier and calls the supplier for each get) seems like a terrible idea. That said, apparently you just want to read n objects from a Supplier and store them in a list. In that case, Sean's answer is probably best.

Just for fun though, here's another way you could create an ImmutableList of size n by calling a Supplier n times (transform, limit and cycle all from Iterables):

public static <T> ImmutableList<T> nInstances(int n, Supplier<T> supplier) {
  return ImmutableList.copyOf(transform(
      limit(cycle(supplier), n), Suppliers.<T>supplierFunction()));
}

I uh... wouldn't recommend this over a straightforward loop implementation though (for readability reasons mostly).

like image 167
ColinD Avatar answered Jan 31 '23 21:01

ColinD