ACA Blog

ACA Blog

March 2021


A few Java 8 Lambda impressions

Jan Van den BerghJan Van den Bergh

Yesterday I attended the BeJUG session on Lambda expressions in Java 8, which was given by professor Eric Steegmans from the K.U.Leuven. Although Java 8 is scheduled to be released next year, it was nice to already learn about it. In this post you will find some points made in the session and a few personal observations.

Required software

You really need IntelliJ IDEA if you want to start playing around with Java 8, since Eclipse doesn’t support it yet. The Community Edition should be enough.
In addition you need to install the Java 8 Early Access version.

At a glance

At first sight, Lambda expressions are nothing more than syntactic sugar offered by the compiler, which allows you to more easily create anonymous classes. For instance, the block

can now be replaced with

Other forms exist as well. Suppose you have a static method Test.check(int i) that contains the same check. In that case you could write:

Streams API

Another nice addition is the Streams API added to the java.util.Collection interface. It makes it a lot easier to iterate over the items of a class. For instance, to print all integers in the collection that are larger than 200, the following code suffices:

Suppose you have a collection of Account objects that have a balance. To get the sum of the balances that are below zero, you can do the following:

In this example, we describe a map – reduce algorithm to get the result. The implementation of the stream method determines the strategy to calculate the results. It becomes very easy to do this in a parallel way: simply replace stream() with parallelStream().

Note that the reduce() method returns an object of type Optional. The possibility exists that there are no items left to reduce. In that case the result will not contain a value.

Diving Deeper

Although lambda expressions seem to be nothing more than a nice addition to the compiler, the implementation goes farther than that. The Java VM has been extended to deal with them in a more efficient way. With the traditional approach our previous example would result in an additional three anonymous classes, named Test$1.class, Test$2.class andTest$3.class. However, this is not the case. Instead the lambda expressions are converted into classes at runtime.

The lambda expression syntax was not the only thing that was added to Java to accomodate a functional programming style. In addition there are:

More information

At this moment the Java 8 Lambda specification (JSR 335) is stable enough and lots of information can be found on the internet. You can also find some talks on