211.
The following are some examples of lambda expressions:
Example 1– Single parameter, No return value
str–> System.out.println(str);
This lambda expression accepts
one parameter and uses a
Sysout statement to print it. It does not return any value.
Example 2– Multiple parameters and a return value
(num1, num2)–> num1+num2;
This lambda expression accepts two parameters and returns the
result of adding them. The return keyword is not specified
explicitly here.
Example 3– No parameter, lambda body and return value
()–>{
//doing something here
return 0;
}
This lambda expression does not accept any parameters. It has a
body that executes some code. It returns the value 0.
Write a code sample that creates a Functional interface
and use a Lambda expression to implement it.
Answer:
A functional interface is an interface with just one abstract
method. Consider the following functional interface:
@FunctionalInterface
public interface StringConverter {
212.
public String convert(String s);
}
This code defines a functional interface called
StringConverter with a method called convert. The
convert method accepts a String value and returns a String.
A lambda expression provides an implementation
for the method
in the functional interface.
So, you can then implement StringConverter interface using a
lambda expression as follows:
StringConverter converter = (str)–> str.toUpperCase();
Here, the StringConverter is implemented via a lambda
expression that converts the input
String to uppercase and
returns it.
Do'stlaringiz bilan baham: