Lambda Expression Java Tutorial with Examples

java lambda expressions tutorial,Lambda Expression Java Example,Lambda Expression Java 8 Example, java 8 lambda syntax,java 8 lambda expressions example.

Java Lambda Expressions Tutorial

A lambda expression java can be understood as a concise representation of an anonymous function that can be passed around. It doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown. That’s one big definition; let’s break it down:

  • Anonymous—We say anonymous because it doesn’t have an explicit name like a method would normally have; less to write and think about!
  • Function—We say function because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.
  • Passed around—A lambda expression can be passed as argument to a method or stored in a variable.
  • Concise—You don’t need to write a lot of boilerplate like you do for anonymous classes.

If you’re wondering where the term lambda comes from, it originates from a system developed in academia called lambda calculus, which is used to describe computations. Why should you care about lambda expressions? You saw in the previous chapter that passing code is currently tedious and verbose in Java. Well, good news! Lambdas fix this problem; they let you pass code in a concise way. Lambdas technically don’t let you do anything that you couldn’t do prior to Java 8. But you no longer have to write clumsy code using anonymous classes to benefit from behavior parameterization! Lambda expressions will encourage you to adopt the style of behavior parameterization that we described in the previous chapter. The net result is that your code will be clearer and more flexible. For example, using a lambda expression you can create a custom Comparator object in a more concise way

Lambda Expression Java Example

Before:

Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};

After (with lambda expressions):

Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

You must admit that the code looks clearer! Don’t worry if all the parts of the lambda expression exemple don’t make sense yet; we’ll explain all the pieces soon. For now, note that you’re literally passing only the code that’s needed to compare two apples using their weight. It looks like you’re passing the body of the method compare. You’ll learn soon that you can simplify your code even more. We’ll explain in the next section exactly where and how you can use lambda expressions.

The lambda we just showed you has three parts, as shown in this Lambda Expression java 8 Example:

(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
  • A list of parameters—In this case it mirrors the parameters of the compare method of a Comparator—two Apples.
  • An arrow—The arrow -> separates the list of parameters from the body of the lambda.
  • The body of the lambda—Compare two Apples using their weights. The expression is considered the lambda’s return value.

Java 8 Lambda Expressions Example

To illustrate further, the following listing shows five examples of valid lambda expressions in Java 8.
(String s) -> s.length()
(Apple a) -> a.getWeight() > 150
(int x, int y) -> {
System.out.println("Result:");
System.out.println(x + y);
}
  • Takes one parameter of type String and returns an int. It has no return statement as return is implied.
  • Takes one parameter of type Apple and returns a boolean (whether the apple is heavier than 150 g).
  • Takes two parameters of type int and returns no value (void return). Its body contains two statements.
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())
  • Takes two parameters of type Apple and returns an int representing the comparison of their weights
  • Takes no parameterand returns the int 42


This java 8 lambda syntax was chosen by the Java language designers because it was well received in other languages, such as C# and Scala. JavaScript has a similar syntax. The basic syntax of a lambda is either (referred to as an expression-style lambda)
(parameters) -> expression
or (note the curly braces for statements, this lambda is often called a block-style lambda)
(parameters) -> { statements; }
As you can see, lambda expressions follow a simple syntax. Working through quiz 3.1 should let you know if you understand the pattern.

java 8 lambda syntax

Based on the java 8 lambda syntax rules just shown, which of the following are not valid lambda
expressions?
1 () -> {}
2 () -> “Raoul”
3 () -> { return “Mario”; }
4 (Integer i) -> return “Alan” + i;
5 (String s) -> { “Iron Man”; }
Answer:
4 and 5 are invalid lambdas; the rest are valid. Details:
1 This lambda has no parameters and returns void. It’s similar to a method
with an empty body: public void run() { }. Fun fact: this is usually called
the burger lambda. Take a look at it from the side, and you will see it has a
burger shape with two buns.
2 This lambda has no parameters and returns a String as an expression.
3 This lambda has no parameters and returns a String (using an explicit
return statement, within a block).
4 return is a control-flow statement. To make this lambda valid, curly braces
are required as follows: (Integer i) -> { return “Alan” + i; }.
5 “Iron Man” is an expression, not a statement. To make this lambda valid, you
can remove the curly braces and semicolon as follows: (String s) -> “Iron

Man”. Or if you prefer, you can use an explicit return statement as follows:
(String s) -> { return “Iron Man”; }.

java 8 lambda syntax

Lambda Expression Java with examples of use cases

Use case Lambda Expression Java Exemple
A boolean expression
Creating objects
Consuming from an object


Select/extract from an object
Combine two values
Compare two objects

(List<String> list) -> list.isEmpty()
() -> new Apple(10)
(Apple a) -> {
System.out.println(a.getWeight());
}
(String s) -> s.length()
(int a, int b) -> a * b
(Apple a1, Apple a2) ->
a1.getWeight().compareTo(a2.getWeight())


Keywords:

java lambda expressions tutorial,Lambda Expression Java Example,Lambda Expression Java 8 Example, java 8 lambda syntax,java 8 lambda expressions example.