Java 8 用供应商填充数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25077203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:17:55  来源:igfitidea点击:

Java 8 fill array with supplier

javafunctional-programmingjava-8

提问by gontard

Is there a way to fill an array using java 8 Supplier?

有没有办法使用 java 8 填充数组Supplier

I would like to write:

我想写:

Supplier<Object> supplier = () -> new Object();
Object[] array = new Object[size];
Arrays.fill(array, supplier);

Note: I know i could write my own method.

注意:我知道我可以编写自己的方法。

回答by Pshemo

In case you want to create new arrayfilled with results generated by Supplier you can use

如果您想创建填充由供应商生成的结果的新数组,您可以使用

Object[] array = Stream.generate(supplier)
                       .limit(arraySize)
                       .toArray(); // will generate new *Object[]* array

For different types than Object[]you can use toArray(IntFunction<YourType[]> generator);like toArray(YourType[]::new)(credits to@Holger).

对于不同类型比Object[]你可以使用toArray(IntFunction<YourType[]> generator);toArray(YourType[]::new)学分@Holger)。

String[] array  = Stream.generate(supplier)
                        .limit(10)
                        .toArray(String[]::new); //now *String[]* array will be returned

Streams also allow us to work with most "popular" primitive types which are intlongand double. For instance we can use IntStream#toArrayto create int[]holding elements from IntStream. To "fill" IntStreamwith elements from supplier we can use IntStream.generate(intSupplier)like

Streams 还允许我们处理大多数“流行”的原始类型,即intlongdouble。例如,我们可以使用IntStream#toArray创建int[]持有的元素IntStream。要“填充”IntStream来自供应商的元素,我们可以使用IntStream.generate(intSupplier)

int[] array = IntStream.generate(()->1)
                       .limit(5)
                       .toArray(); //returns `new Int[]{1,1,1,1,1}


In case when you want to fill already existing arraywith data from Supplier see answerposted by Stuart Marksbased on Arrays.setAll(array, supplier)which aside from handling arrays of objects also supports somearrays of primitive types: double[]int[]and long[].

如果您想用来自供应商的数据填充现有数组,请参阅Stuart Marks发布的答案,其中除了处理对象数组外,还支持一些原始类型的数组:和。Arrays.setAll(array, supplier)double[]int[]long[]

Other alternativeis to use use creativesolution from @Hogler'scomment:

其他替代方法是使用@Hogler评论中的创造性解决方案:

Arrays.asList(array).replaceAll(x -> supplier.get()); 
//you can even overwrite a range using `subList`

just be aware of its problems with array of primitive types explained by Jon Skeet at https://stackoverflow.com/a/1467940.

请注意 Jon Skeet 在https://stackoverflow.com/a/1467940解释的原始类型数组的问题。

回答by Stuart Marks

In java.util.Arraysthere is

java.util.Arrays

<T> void Arrays.setAll(T[] array, IntFunction<T> generator)

This doesn't take a supplier; instead it takes an IntFunctionwhose input argument is the array index being filled. If your objects aren't dependent upon the destination array index, you can disregard the parameter and call a supplier like this:

这不需要供应商;相反,它需要一个IntFunction其输入参数是正在填充的数组索引。如果您的对象不依赖于目标数组索引,您可以忽略该参数并像这样调用供应商:

Arrays.setAll(array, i -> supplier.get());

There are overloads for arrays of primitives as well as arrays of reference type. There is also a corresponding family of methods parallelSetAll()that does the same thing, except in parallel. (It uses streams internally.)

有原始数组和引用类型数组的重载。parallelSetAll()除了并行之外,还有一个相应的方法系列可以做同样的事情。(它在内部使用流。)

回答by user253751

You could easily write your own:

您可以轻松编写自己的:

public static <T> void fillArray(T[] array, Supplier<? extends T> supplier) {
    for(int k = 0; k < array.length; k++)
        array[k] = supplier.get();
}

回答by Syam S

Alternative to Pshemo's solution you could use map method.

您可以使用 map 方法替代 Pshemo 的解决方案。

Object[] array = new Object[size];
array = Arrays.stream(array).map(a -> new Object()).toArray();