Java 8 – lambda expressions


Lambda expression were introduced in Java 8.

Here’s a simple example that illustrates how to use lambda expressions, and how they make your code simpler and more expressive (not to mention background optimizations by the compiler).

Consider this code that iterates over a list to print out its elements.

List<Integer> values = Arrays.asList(1,2,3,4);
for (int i = 0; i < values.size(); i++){

What we’re really trying trying to do is print out each element of the array but we’ve had to write a whole bunch of ceremonial code around the that main task of interest to us. This may not bug you much but that’s because it’s familiar. Lambda expressions are (at present) less familiar. But they are simpler. And simpler code, is more readable code. It communicates the essence of what it’s trying to do more readily. Java 8 introduces two new things – internal iteration with forEach(...) on collections and lambda expressions – that can turn the big messy for loop above into something much more to the point.

values.forEach((Integer value) -> System.out.println(value));

or the following, since Java knows than each element in a collection of `Integer`s is going to be an Integer.

values.forEach(value -> System.out.println(value));

Remember how lambda expressions are essentially anonymous methods? In the code above

  • the bit before the -> are the arguments to the method ((Integer value));
  • after the -> comes the body of the method; and
  • the return type is implied based on the method to which this lambda expression is being passed. For example, a forEach(...) call understandably doesn’t need a return type (i.e. void), it just wants to know what to do for each element of the collection instance it’s invoked on.

Based on this great talk by Venkat Subramaniam at SpringOne2GX 2014


Leave a Reply

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

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s