Warm tip: This article is reproduced from serverfault.com, please click

For loop

发布于 2013-05-15 16:13:50

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]

This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?

Questioner
Kacper Lubisz
Viewed
0
2,865 2019-12-30 07:06:33

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