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).
Like many other idioms, Java 8 finally delivers with a short and sweet version that doesn't need any external libraries. You can now do this with Streams.generate(Supplier<T> s)
. For example, for n
instances of Foo
:
Streams.generate(Foo::new).limit(n)...
You'd finish that line off in different ways depending on how you wanted to create your List. For example, for an ImmutableList
:
ImmutableList.copyOf(Streams.generate(Foo::new).limit(n).iterator());
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;
}
精彩评论