Fill arrays with ranges of numbers

前端 未结 6 622
甜味超标
甜味超标 2020-11-29 06:20

Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?

e.g.

int[] arr = new int[1000];
arr=(1..500,3         


        
6条回答
  •  一个人的身影
    2020-11-29 07:09

    For those still looking for a solution:

    In Java 8 or later, this can be answered trivially using Streams without any loops or additional libraries.

    int[] range = IntStream.rangeClosed(1, 10).toArray();
    

    This will produce an array with the integers from 1 to 10.

    A more general solution that produces the same result is below. This can be made to produce any sequence by modifying the unary operator.

    int[] range = IntStream.iterate(1, n -> n + 1).limit(10).toArray();
    

提交回复
热议问题