Java 8 Lambda : the very basics

Functional interface

In many cases – when talking about Java 8 – lambda-functions are the first thing that comes up. I found it a concept hard to grasp, as it slightly changes the way you think about coding. In this blog, I would like to show you some very simple examples, and explain what is what in the lambda world.

In versions prior to Java 8, we had SAM interfaces : Single Abstract Method-interfaces. In Java 8, the concept of SAM-interfaces has been re-created and called “functional interfaces”. These interfaces can be used in lambda-expressions. Here’s a definition of such an interface that we will be using in the examples.

interface MyCalculator {
	public double calculate(double val1, double val2);

The “FunctionalInterface” annotation is used to generate compiler level errors, when the interface is not a functional interface. A functional interface is an interface with 1 abstract method. The annotation is not required, but improves the readability of your code.

Using the lambda

When the functional interface is created, you can declare a variable to be assigned with a lambda-expression.

MyCalculator multiply = (value1, value2) -> value1 * value2;
MyCalculator sum = (value1, value2) -> value1 + value2;
System.out.println(“multiply = “+multiply.calculate(5,6));
System.out.println(“sum = “+sum.calculate(5,6));

Generates following output:
multiply = 30.0
sum = 11.0

So if you are wondering what is what in a lambda-expression :
Before the arrow = variables of your function
After the arrow = code to be executed by the abstract method of the functional interface

If we would do this the ‘old-school’ way, our code would look like this :

MyCalculator multiply = new MyCalculator() {
	public double calculate(double val1, double val2) {
					return val1 * val2;
MyCalculator sum = new MyCalculator() {
	public double calculate(double val1, double val2) {
					return val1 + val2;
System.out.println("multiply = "+multiply.calculate(5,6));
System.out.println("sum = "+sum.calculate(5,6));

The advantage of lambda is pretty clear : less code, better readability.

If you want to define more than 1 line of code, write it like this :

MyCalculator calc = (value1, value2) -> {
			System.out.println("Before calculating");
			double result = value1* value2* 3;
			System.out.println("After calculating");
			return result;
System.out.println(calc.calculate(3, 4));

Generates the following output:
Before calculating
After calculating

Use of non-local variables in lambda expressions

In versions prior to Java 8, the following code :

Calendar cal = Calendar.getInstance();
MyCalculator sum = new MyCalculator() {
	public double calculate(double val1, double val2) {
		return val1 + val2;

would generate an error :
“Cannot refer to the non-final local variable cal defined in an enclosing Scope”
on statement

because the variable “cal” was not defined as final.

The Java 8 compiler has a new capability that will convert non-local variables, used in lambda-expressions and anonymous inner class methods, automatically to final.
So in Java 8, this code will actually compile. Even better: now, we can write the previous code as a lambda-expression :

Calendar cal = Calendar.getInstance();
MyCalculator sum2 = (value1,value2) -> {
			return value1+value2;

Streams API and lambdas

New in Java 8 is the Stream API ( According to Oracle’s documentation : “A stream is not a data structure that stores elements; instead, it transports elements from a source (data structure, array, generator function, or an I/O channel), through a pipeline of computational operations.”

This is where the lambdas make their entrance, as a pipeline is a sequence of lambda expressions that can process or interrogate every element in the stream. In short : by using streams and lambda’s, we can execute a whole bunch of operations on a Collection, all in 1 statement.

Suppose we want to print out every even number from a list of Integers.

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> evenList = -> value%2==0).collect(Collectors.toList()); -> System.out.println(value));

In the second line, the filter method will return the values matching the predicate, in this case, a lambda-expression. The collect method will return the result list.
On the third line, we use a stream to print out every value of our new list, containing the even values.

If you had to write the above code in Java 7, you would need more code, so more possible flaws, less readability.
But there is more :

Map<Person.Sex, List<Person>> byGender =;

In 1 line of code, from a list of person objects, we create a map with the gender as the key.

Read the Java Doc on java.util.streams, and you’ll discover a whole new way of writing code, including parallel processing of your stream. Also, check out the Collectors API where you can find methods to convert your collections into other sorts of collections, without any for loops, etc…

The better you understand lambdas and streams, the more you’ll understand why they are such a hot issue in the Java world, the more you’ll improve your code!

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

About Chris Noë