Using IntStream.range instead of an ordinary for loop

Java 8 and Streams are really nice. They can even make look ordinary for loops much cooler. Assume the following snippet:

for (int i = 0; i < 10; i++) {
elements[i] = new MyModel(i);
}

This can also be written with the IntStream class.

IntStream.range(0, 10).forEach(i -> elements[i] = new MyModel(i));

I think the second statement looks much cooler.

Anyone knows if the old for loop is more efficient? I would assume IntStream is handled well enough be the Java compiler but did not check.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse, Lars Vogel. Bookmark the permalink.

16 Responses to Using IntStream.range instead of an ordinary for loop

Comments are closed.