Parallel Looping Constructs in Java (revisited)

Two years ago, I blogged about parallel for each construct using a very early version of lambda prototype compiler. At that time, Data Parallelism was already available in C# TPL, but Java designers were hard at work in bringing this idiom to Java.


Parallel.ForEach(students, student => {
student.GradePointAverage = student.Tests.Select(test => test.Grade * test.Weight).Sum();
} );

view raw

Parallel.cs

hosted with ❤ by GitHub

Lambda expressions support in Java 8 is here for everyone to give it a spin. Functional touch to Collections library makes it a breeze to program in Java. you get this one-liner using Java 8 Stream API.


students.parallelStream().forEach(student -> {
student.GradePointAverage = student.Tests.parallelStream().mapToDouble(test -> test.Grade * test.Weight).sum();
});

view raw

Parallel.java

hosted with ❤ by GitHub

There are more such one-liners you can think of using parallel constructs in Java 8. Here is another teaser, send an email blast to all customers.


addresses.parallelStream().forEach(address -> sendMail(address));

view raw

Parallel.java

hosted with ❤ by GitHub

Streams API brings several of the LINQ as well as PLINQ awesomeness to Java Collections library. Here is an adhoc query over a collection using the new Streams API.


// Print the names of albums that have at least one track rated four or higher, sorted by name.
albums.stream()
.filter(a -> a.tracks.stream().anyMatch(t -> (t.rating >= 4)))
.sorted(comparing((Album album) -> album.name))
.forEach(album -> System.out.println(album.name));
// Merge tracks from all albums
List<Track> allTracks = albums.stream()
.flatMap((Album album) -> album.tracks.stream())
.collect(toList());
// Group album tracks by rating
Map<Integer, List<Track>> tracksByRating = allTracks.stream()
.collect(groupingBy(Track::getRating));

view raw

Item10.java

hosted with ❤ by GitHub

Check it out here for more one-liners. You may want to checkout this article that compares LINQ with Java Streams API. While, there are constraints with the Java Streams proposal, it hits the right balance and there is a pedagogical value to it as well, keeping majority Java developers happy.

Enjoy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s