Java 8 fill array with supplier

后端 未结 4 1737
执念已碎
执念已碎 2021-01-17 07:53

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

I would like to write:

Supplier supplier = () -> new Object();
Object[] arr         


        
      
      
      
4条回答
  •  孤城傲影
    2021-01-17 08:31

    In case you want to create new array filled 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 generator); like toArray(YourType[]::new) (credits to @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 int long and double. For instance we can use IntStream#toArray to create int[] holding elements from IntStream. To "fill" IntStream with elements from supplier we can use IntStream.generate(intSupplier) like

    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 array with data from Supplier see answer posted by Stuart Marks based on Arrays.setAll(array, supplier) which aside from handling arrays of objects also supports some arrays of primitive types: double[] int[] and long[] .

    Other alternative is to use use creative solution from @Hogler's comment:

    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.

提交回复
热议问题