Java Lambda Expressions Tutorial

Java 8 introduced Lambda Expressions and is one of the biggest, if not the biggest, feature that was introduced because Lambda expression makes functional programming possible and it makes your code way cleaner and overall simplifies the whole code implementation drastically.

For example, when you have to work with anonymous class and that class is very simple, for example containing only a couple (or even less) methods, you will come across a very unclear and hard to read/maintain syntax. This is when Lambda expressions’ role comes into play.

java-featured-image

Let’s compare the use of Lambda expression and non-use of Lambda expression

Let’s pretend there is a class that has a method that sorts elements in ascending order by default (like Comparator for example). This class uses compare to sort elements out. Let’s override it.

non-use of Lambda expression

Comparator<Double> sorter = new Comparator<Double>() {
   @Override
   public int compare(Double x, Double y) {
      return y.compareTo(x);
   }
};

use of Lambda expression

Comparator<Double> lambdaComparator = (x, y) -> y.compareTo(x);

I am sure you can notice the difference between the two approaches. Both of them result in the same thing which is reversing the order this method sorts element (from ascending to descending, jokes on you Comparator!).

So just by looking at this example, one key advantage of using lambda expression would be that there is less code to type. That’s a huge example for us lazy programmers out there. However, one could argue that due to this simplicity, it actually makes it harder to remember the syntax. And that’s true, so that would be one disadvantage. At first, the syntax might be the bit hard-to-remember type but once you remember it, you will be able to write clean code that also allows you to implement the Functional interface.

Let’s see some more examples of Lambda expression.

First, the syntax, as I said before, it is a bit intimidating at first.

If the function you are “overriding” does not have any parameters, you can simply type ()->{body}. If on the other hand, you have got only 1 parameter, you would type (x)->{body}. Same for two and more parameters, you would have (x,y,z..)->{body}.



Looping

import java.util.*;  
public class LambdaExpressionDemo {  
    public static void main(String[] args) {  
        List<int> listOfNumbers = new ArrayList<int>();  
        listOfNumbers.add(1);  
        listOfNumbers.add(2);  
        listOfNumbers.add(3);  
        listOfNumbers.add(4);  
        listOfNumbers.add(5);  
        listOfNumbers.add(6);  
        listOfNumbers.add(7);  
        listOfNumbers.add(8);  
          
        listOfNumbers.forEach(  
            (num) -> System.out.println(num)  
        );  
    }  
}

Notice how in the body of the forEach loop, I omitted the ‘{ }’ braces. That’s because the body consists of only one line. If I had two or more lines, let’s say another print statement, then I would have the braces, like so:

import java.util.*;  
public class LambdaExpressionDemo {  
    public static void main(String[] args) {  
        List<int> listOfNumbers = new ArrayList<int>();  
        listOfNumbers.add(1);  
        listOfNumbers.add(2);  
        listOfNumbers.add(3);  
        listOfNumbers.add(4);  
        listOfNumbers.add(5);  
        listOfNumbers.add(6);  
        listOfNumbers.add(7);  
        listOfNumbers.add(8);  
          
        listOfNumbers.forEach(  
            (num) -> {
                 System.out.println(num);
                 System.out.println(num);   
        );  
    }  
}

Returning value from Lambda expressions

You can also return values, just like in methods, using lambda expression. One key to notice here is that return keyword is optional. You can omit it, the compiler knows its job.

The syntax is similar to what we have been using before.

(x, y) -> {

    return x > y;

}

So if we look again on what Lambda expressions offer us, we can conclude that it provides us with optional type declaration (no need to declare the type of the paramater), optional curly braces, optional return keyword (as the compiler automatically returns the value if the body has a signle expression to the return value) and optional parenthesis around the parameter.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments