Java 8 fill array with supplier

后端 未结 4 1747
执念已碎
执念已碎 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:20

    In java.util.Arrays there is

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

    This doesn't take a supplier; instead it takes an IntFunction whose 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:

    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.)

提交回复
热议问题