For loop - like Python range function

后端 未结 9 1573
情歌与酒
情歌与酒 2020-12-30 21:45

I was wondering if in Java there is a function like the python range function.

range(4)

and it would return

[0,1,2,3]
         


        
9条回答
  •  臣服心动
    2020-12-30 22:37

    Java 8 (2014) has added IntStream (similar to apache commons IntRange), so you don't need external lib now.

    import java.util.stream.IntStream; 
    
    IntStream.range(0, 3).forEachOrdered(n -> {
        System.out.println(n);
    });
    

    forEach can be used in place of forEachOrdered too if order is not important.

    IntStream.range(0, 3).parallel() can be used for loops to run in parallel

提交回复
热议问题