简体   繁体   English

guava-libraries:列出n个实例

[英]guava-libraries: List with n instances

The Java Collections class has the following method: Java Collections类具有以下方法:

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. 我需要一个类似的方法,但稍微更通用,它提供给定类的n个实例。 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. 特别是,如果supplierSupplier.ofInstance(o) ,我们会得到与nCopies()方法相同的行为。 Is there such a method somewhere in the Guava API? 在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. 不,没有,任何等效的构造(只存储int n和供应商,并为每个get调用供应商)似乎是一个可怕的想法。 That said, apparently you just want to read n objects from a Supplier and store them in a list. 也就是说,显然您只想从Supplier读取n个对象并将其存储在列表中。 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 ): 只是为了好玩,这是另一种方法,您可以通过调用Supplier n次来创建大小为n的ImmutableListtransformlimitcycle所有来自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. 像许多其他习语一样,Java 8最终提供了一个简短而又甜蜜的版本,不需要任何外部库。 You can now do this with Streams.generate(Supplier<T> s) . 您现在可以使用Streams.generate(Supplier<T> s)执行此操作。 For example, for n instances of Foo : 例如,对于Foo n实例:

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM