简体   繁体   English

是否存在通过多次调用函数来填充列表的Java方法?

[英]Is there a Java method that fills a List by calling a function many times?

Is there something like this in the standard library? 标准库中是否有类似的东西? It fills a List<T> by calling source.get() : 它通过调用source.get()填充List<T>

public static <T> List<T> listFromFunc(int size, Supplier<T> source) {
    return IntStream.range(0, size)
            .mapToObj(i -> source.get())
            .collect(Collectors.toList());
}

I am afraid not, but you can improve readability of your code with this construct 恐怕不是,但是您可以使用此结构提高代码的可读性

Stream.generate(source).limit(size).collect(Collectors.toList())

Although as Brian Goetz mentioned your original version will parallelize much better. 尽管正如Brian Goetz 提到的那样,您的原始版本将更好地并行化。

Here's another variation: 这是另一种变化:

static <T> List<T> listFromFunc(int size, Supplier<T> source) {
    return Collections.nCopies(size, "").stream()
        .map(o -> source.get())
        .collect(Collectors.toCollection(() -> new ArrayList<>(size)));
}

This enables stream to be SIZED throughout. 这使得流被SIZED贯穿始终。 Collections.nCopies().stream() actually uses IntStream.range() internally so it isn't faster or anything, though. Collections.nCopies().stream()实际上在内部使用IntStream.range()因此它不是更快,也不是任何东西。

Using Collectors.toCollection() enables you to control the concrete type of the list, which toList() does not. 使用Collectors.toCollection()可以控制列表的具体类型,而toList()则不能。 In the sequential case, this also allows you to pre-size the list, avoiding copying that might occur as elements are added to the list. 在顺序情况下,这还允许您预定义列表的大小,避免在元素添加到列表时可能发生的复制。

(Fair warning: in JDK 8, toList() creates an ArrayList , but we might change this in JDK 9 to return a list type that's more amenable to appending.) (公平警告:在JDK 8中, toList()创建一个ArrayList ,但我们可能会在JDK 9中对此进行更改,以返回更适合附加的列表类型。)

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

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