Java 8: From Ordinary For-Loop To An IntStream

Legacy:


for (int i = 0; i < 10; i++) {
	System.out.println(i);
}

Fancy:


IntStream.range(0, 10).forEach(
	nbr -> System.out.println(nbr)
);

Why? ...because the execution of the following snippet takes 1 second and not 10 seconds:


IntStream.range(0, 10).parallel().forEach(
	nbr -> {
	try {
		Thread.sleep(1000);
		} catch (InterruptedException ex) {}
        	System.out.println(nbr);
        }
);

Comments:

Nitpick mode: it only takes 1 second if you have at least 10 cores...

Posted by Bert-Jan on January 28, 2014 at 02:01 PM CET #

Actually it took 3 seconds to show 2, 7, 8, 6, 4, 1, 9, 5, 3, 0

:)

But I have only four available processors ;)

Fancy and cool anyway

Posted by Javier Beneito Barquero on February 04, 2014 at 08:02 PM CET #

Actually it took 3 seconds to show an unordered randomly list :)

But I have only four available processors ;)

Fancy and cool anyway

Posted by 94.126.240.3 on February 04, 2014 at 08:03 PM CET #

@Bert-Jan: I dont think this is right.
Thread.sleep() does not perform busy waiting, so all Threads will wait ~1 second in parallel. With one core System.out.println() will be executed sequentially in an order determined by the Scheduler.

Posted by gustav on February 05, 2014 at 03:26 PM CET #

great

Posted by 203.94.71.188 on July 21, 2016 at 11:34 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License