Java 8 – Lambda Expressions

Lambda expressions are new feature in Java 8. We now can represent one method interface by using an expression.

I. Overview

1. Pass a method as argument

Assume that we have 2 math operations: addition and subtraction. Those operations will be chosen in specific cases with 2 numbers: a and b. So the math operation is considered as an argument to method:


int doMathOperation(int a, int b, MathOperation mathOperation) {...}

To make thing done, in normal approach, we declare an interface:


public interface IMathOperation {
	int run(int a, int b);
}

and two implementations:


public class Addition implements IMathOperation {

	@Override
	public int run(int a, int b) {
		return (a + b);
	}
}

public class Subtraction implements IMathOperation {

	@Override
	public int run(int a, int b) {
		return (a - b);
	}
}

Main function will be:


int doMathOperation(int a, int b, IMathOperation mathOperation) {
   return mathOperation.run(a, b);
}

And the context to use them:


public static void main(String[] args) {
	IMathOperation addition = new Addition();
	IMathOperation subtraction = new Subtraction();

	// Anonymous Inner Class
	IMathOperation multiplication = new IMathOperation() {
		
		@Override
		public int run(int a, int b) {
			return (a * b);
		}
	};
	
	System.out.println(doMathOperation(2, 1, addition));
	System.out.println(doMathOperation(2, 1, subtraction));
	System.out.println(doMathOperation(2, 1, multiplication));
}

An Anonymous Inner Class is used instead of creating a implementation class for IMathOperation interface.

2. Using Lambda Expressions

We can see that it is not easy to pass a method to a function in Java, so Java 8 provides a new feature called Lambda Expressions.
Using this kind of feature, we only need to create a interface like the old interface.


public interface IMathOperation {
	int run(int a, int b);
}

All implementations of the interface and Anonymous Inner Class will be replaced by very simple expressions:


	static int doMathOperation(int a, int b, IMathOperation mathOperation) {
		return mathOperation.run(a, b);
	}

	public static void main(String[] args) {
//		IMathOperation addition = new Addition();
//		IMathOperation subtraction = new Subtraction();

//		IMathOperation multiplication = new IMathOperation() {
//			
//			@Override
//			public int run(int a, int b) {
//				return (a * b);
//			}
//		};
		
		IMathOperation addition = (int a, int b) -> a + b;
		IMathOperation subtraction = (int a, int b) -> a - b;
		IMathOperation multiplication = (int a, int b) -> a * b;
		
		System.out.println(doMathOperation(2, 1, addition));
		System.out.println(doMathOperation(2, 1, subtraction));
		System.out.println(doMathOperation(2, 1, multiplication));
	}

II. Lambda Expressions

1. Syntax

Argument ListArrow TokenBodyNote
(arg1, arg2…)->{ body }
(int a, int b)->a + bwith type declaration
(a, b)->a + bno type declaration
(int a, int b)->{return (a + b)}with return statement
a->a*a*ano parenthesis
()->42no arguments
(String s)->{System.out.print(s);}returns nothing

– A lambda expression can have zero, one or more parameters.
– No need to declare type of a parameter.
– No need to write parenthesis around parameter if there is only one parameter (required if more).
– No need to use curly braces in expression body if there is only one statement (required if more).
– No need to use return keyword if there is only one statement. The compiler returns the value automatically.

2. Common use cases

Using Lambda Expressions make beautiful and lean code than using Anonymous Inner Class.
Runnable Lambda: java.lang.Runnable is an example of Functional Interface which we will learn in the next article.


// Runnable Anonymous Class
Runnable r1 = new Runnable() {

	@Override
	public void run() {
		System.out.println("Hello world!");
	}
};

// Lambda Runnable
Runnable r2 = () -> System.out.println("Hello world!");

Comparator Lambda:


// Sort with Comparator Inner Class
Collections.sort(customers, new Comparator() {
	public int compare(Customer c1, Customer c2) {
		return c1.getLastName().compareTo(c2.getLastName());
	}
});

// Comparator Lambda
Collections.sort(customers, (Customer c1, Customer c2) -> c1.getLastName().compareTo(c2.getLastName()));

Listener Lambda(also a Functional Interface):


// Listener Anonymous Class | ActionListener
JButton testButton = new JButton("Test Button");
testButton.addActionListener(new ActionListener() {
	@Override
	public void actionPerformed(ActionEvent ae) {
		System.out.println("Listener Anonymous Class Detected");
	}
});

// Listener Lambda
testButton.addActionListener(e -> System.out.println("Lambda Listner Detected"));

III. Source code

Technology:
– Java 8
– Eclipse Mars.1 Release (4.5.1)
lambdaexpersion



By grokonez | October 20, 2016.

Last updated on April 9, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*