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 a little more general, which provides n instances of this class. Sort of:

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

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

Thanks.

+4
source share
3 answers

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; } 
+2
source

No, no, and any equivalent construct (which simply stores int n and the provider and calls the provider for each get ) seems like a terrible idea. However, apparently, you just want to read n objects from Supplier and save them in a list. In this case, Sean's answer is probably the best.

Just for fun, but here you can create an ImmutableList size n by calling Supplier n times ( transform , limit and cycle all of 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 ... would not recommend this compared to a simple loop implementation (for greater readability).

+4
source

Like many other idioms, Java 8 finally ships with a short and sweet version that does not 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 will end this line in different ways, depending on how you want to create your list. For example, for an ImmutableList :

 ImmutableList.copyOf(Streams.generate(Foo::new).limit(n).iterator()); 
+2
source

Source: https://habr.com/ru/post/1332918/


All Articles