Lambda Expressions
Start course

In this lesson, we will learn the Lambda Expressions.

Learning Objectives

  • Marker and Functional Interfaces
  • Lambda Expressions
  • Predicate Interface
  • Static Import

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams


  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge

Hi there. In this video, we'll talk about the Lambda Expression in Java. Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. The lambda expression provides the implementation of the functional interface. If you remember, we talked about the anonymous classes in the previous sections. One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method i.e. if it's a functional interface, then the syntax of anonymous classes may seem unwieldly and unclear. In those cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expression enables you to do this, to treat functionality as a method argument or code as data. Now, let's look at the syntax of the lambda expression. Java lambda expression consists of three components. The first one is the argument list. 

It can be empty or non-empty as well. The second is the arrow-token. It's used to link arguments list and body of expression. And the last one is the body. It contains expressions and statements for lambda expressions. Okay, after this information about the lambda, let's move on to the Eclipse and get some practice. Since we've done the simple use of lambda before, in this lesson we'll go one step further and build an application that does four operations with lambda. First, let's create a new project. I click the file menu and select the new Java project options. The project name can be LambdaExpression. The Java version will be Java SE 8 or Java SE 1.8. Don't change the other options and click the 'Finish' button. Next, I'll create an interface. I right click on the source folder and select the new interface options. The name of the package can be lambdaexpressionexample and the name of the interface can be CanCalculate, and click the 'Finish' button. Okay, this interface will contain one method and this method will be a void method. In addition, this method will take three parameters, two parameters for the numbers and one parameter for the operator. Let's create the method. void canDoFourOperations (int num1, int num2, char operator). Okay, since this method is an abstract method by default, it will not contain a body. 

Also, we can annotate this interface as a functional interface. This is not mandatory but we declare the interfaces have one method as functional interface. So, above the interface after putting an @ sign, I write FunctionalInterface. Okay, now let's create the test class. I right click on the lambdaexpressionexample package and select the new class options. The class name will be TestLambdaExpression, and I will check the checkbox for the main method and click the 'Finish' button. First, I will create a method outside the main method, public static void showResult() This method will take four parameters. The first parameter will be int number1. The second parameter will be int number2. The third parameter will be the char operator, and the last parameter will be a reference of the CanCalculate interface, calculate. And inside this method, I will call the canDoFourExpressions method of the CanCalculate interface, calculate.canDoFourOperations and this will take three parameters: number1, number2 and the operator. Okay, now let's call the showResult method in the main method. I write showResult. Also, we have to give the necessary parameters to this method. For this, I'll use the Scanner class. Scanner inputScanner = new Scanner( First, I will give a message to the user to enter two numbers. System.out.println("Please enter two numbers: "); 

Also, this method will be the print method instead of println. Now let's get these numbers from users and assign them to variables. int number1 = inputScanner.nextInt(), int number2 = inputScanner.nextInt(). Now, let's give another message to the user to enter the operator. System.out.println("Please select an operator(+, -, *, /): "). This will be the print method again. Now, let's take the operator and assign it to a variable. char operator =; In the previous lessons, we explained the charAt method. The charAt method is used for taking a character input in Java. So, if the user enters two or more operators on the same line, it will deal with only the first operator. If I change this value to 1, it will deal with the second operator. Okay, let's continue. Now I can assign these variables as the parameter to the showResult method. The first parameter will be the number1. The second parameter will be number2. The third parameter will be the operator. So, what are we going to write in the fourth parameter?

The fourth parameter must be a reference of the CanCalculate interface. If I type new CanCalculate here and press 'Enter', as you can see, a code block is created and the canDoFourOperations method is overridden. In fact, an anonymous class is created here. But if you pay attention, it looks quite complicated. At this point, we'll use lambda because there is only one method so we can create a lambda expression instead of this anonymous class. Therefore, let's delete this anonymous class. Yes, now let's create the lambda expression. If you remember, the canDoFourOperations method had three parameters. Let's write these parameters in parentheses first. (num1, num2, operator); 

Of course, you can use different names here. For example, we can write x, y and z. The important thing here is that you know that the first parameter you write represents the first parameter in the canDoFourOperations method. The second represents the second and the third represents the third parameter. If you are aware of this, you can write any name you want. Next, we need to create the lambda symbol, arrow. For this, if you press the minus and greater than keys on the keyboard, you can create the lambda symbol. Finally, we need a pair of curly braces. Yes, that's it. Creating a lambda expression is actually that simple. Don't forget to also close the code block with the semicolon, otherwise, you'll get a compile error. Now we can do the necessary operations in curly brackets. First, I will create a double variable, double result = 0.0. Now I will create a switch-case statement. The switch will receive the z variable representing the operator and depending on what it is, chooses a certain case. The first case value is the additive operator in a single quotation mark because we define the char data type between the single quotes and in the first case, we will do the addition of two numbers. I'll assign x + y to the variable result. x represents the number1 and y represents the number2. Let's copy the code and paste it four times. 

And now, let's make changes for case values and other arithmetic operations. We will use the subtraction operator in the second case, multiplication order in the third case, division operator in the fourth case. Okay, we have four operators, so if the user enters except these four operators, we should warn the user in the default code block. In the default part, we display the invalid operator message to the user by using the print method. And let's display the calculation and result to the user using the println method. Just after the switch statement I write, System.out.println( x + " " + z + " " + y + " = " + result). Also, it's better to close the Scanner object by using the close method. Okay, let's run the code. I will enter 12 and 13 for two numbers and I'll choose the additive operator. But if you notice, the invalid message appears because we forgot to use the break keyword after each case. In this case, the default block, which is the last case, worked. Now, let's add the break keyword for the cases. I'll also add the return keyword for the default block because I want the program to terminate if the user enters an invalid operator. 

Yes, let's run it one more time. I will enter 12 and 13 for two numbers again, and I will choose the additive operator. So, the result is 12 + 13 = 25.0. Okay, let's run the code again. I will enter 12 and 7 and I'll choose the subtraction operator this time. The result is 12 - 7 = 5.0. Okay, let's run the code again. I will enter 13 and 3 and I will choose the multiplication operator. The result is 13 * 3 = 39.0. Okay, let's run the code again. I will enter 15 and 5 and I will choose the division operator. The result is 15 / 5 = 3.0. Okay, finally run the code and I will enter 12 and 4 and I will choose illegal operators this time. The result is invalid operator choice. Yes, so we have developed a calculator similar to the one we developed in previous lessons but this time we used the lambda expression. I hope it was useful for you. Okay, let's take a short break here. See you in the next lesson.


About the Author
Learning Paths

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics