Java: Lambda Expressions - what is it?
Related Videos: Java Lambda Expressions #1 - The Basics (April 2024).
Implementing an interface with only one abstract method is usually relatively confusing. Lambda expressions offer a remedy. How you can use them.
Java: Lambda Expressions
For example, consider the following functional interface: » interface test {void test method (String x); } «.
- Instead of implementing the abstract method in the classic way, you can also save time and use lambda expressions.
- To do this, first implement the interface, then enter the parameters of the abstract method and finally the actual declaration of the method: » Test test = (String x) -> System.out.println (x); ". The operator » -> « was newly introduced for this.
- If the method has no parameters, just leave the parentheses empty. Several parameters are separated as normal with commas.
- If the function should execute several commands, delimit the body of the Lamda function with curly brackets: » Test test = (String x) -> {if (x.length ()> 0) {System.out.println (x) ; } else {System.out.println ("no character"); }}; ".
- Lambda expressions are particularly practical for iterations using ArrayLists. If " list " is an ArrayList, you can, for example, use " liste.forEach ((x) -> System.out.println (x)); «Output all elements of the list.
- You can also use Lambda Expressions to set the return value of the abstract method. Let us consider the interface » interface compute {int compute (int a, int b); } «. With the command » add arithmetic = (int a, int b) -> a + b; For example, a method for summing two numbers is implemented.