How can I generate a list or array of sequential integers in Java?

前端 未结 8 1850
清歌不尽
清歌不尽 2020-11-28 21:54

Is there a short and sweet way to generate a List, or perhaps an Integer[] or int[], with sequential values from some

8条回答
  •  余生分开走
    2020-11-28 22:49

    The following one-liner Java 8 version will generate [ 1, 2 ,3 ... 10 ]. The first arg of iterate is the first nr in the sequence, and the first arg of limit is the last number.

    List numbers = Stream.iterate(1, n -> n + 1)
                                  .limit(10)
                                  .collect(Collectors.toList());
    

提交回复
热议问题