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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With