Does Java 8 provide a good way to repeat a value or function?

后端 未结 5 1029
遥遥无期
遥遥无期 2020-12-02 05:26

In many other languages, eg. Haskell, it is easy to repeat a value or function multiple times, eg. to get a list of 8 copies of the value 1:

take 8 (repeat 1         


        
5条回答
  •  情话喂你
    2020-12-02 05:56

    For this specific example, you could do:

    IntStream.rangeClosed(1, 8)
             .forEach(System.out::println);
    

    If you need a step different from 1, you can use a mapping function, for example, for a step of 2:

    IntStream.rangeClosed(1, 8)
             .map(i -> 2 * i - 1)
             .forEach(System.out::println);
    

    Or build a custom iteration and limit the size of the iteration:

    IntStream.iterate(1, i -> i + 2)
             .limit(8)
             .forEach(System.out::println);
    

提交回复
热议问题