Java8:Lambda Expressions
What is lambda expression:
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and abody. Sometimes a lambda expression is simply called a lambda. The body of a lambda expression can be a block statement or an expression. An arrow (->) is used to separate the list of parameters and the body. The term “lambda” in "lambda expression" has its origin in Lambda calculus that uses the Greek letter lambda (l) to denote a function abstraction.
Exmaples of lambda expressions:
// Takes an int parameter and returns the parameter value incremented by 1
(int x) -> x + 1
// Takes two int parameters and returns their sum
(int x, int y) -> x + y
// Takes two int parameters and returns the maximum of the two
(int x, int y) -> { int max = x > y ? x : y;
return max;
}
// Takes no parameters and returns a string "OK"
() -> "OK"
// Takes a String parameter and prints it on the standard output
(String msg) -> { System.out.println(msg); }
// Takes a parameter and prints it on the standard output
msg -> System.out.println(msg)
// Takes a String parameter and returns its length
(String str) -> str.length()
// Takes no parameters and returns void
() -> { }
Syntax of lambda expressions::
A lambda expression describes an anonymous function. The general syntax for using lambda expressions is very similar to declaring a method.
The general syntax is (<LambdaParametersList>) -> { <LambdaBody> }
A lambda expression consists of a list of parameters and a body that are separated by an arrow (->). The list of parameters is declared the same way as the list of parameters for methods. The list of parameters is enclosed in parentheses, as is done for methods. The body of a lambda expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.
Omitting Parameter Types ::
You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in which the lambda expression is used.
// Types of parameters are declared
(int x, int y) -> { return x + y; }
// Types of parameters are omitted
(x, y) -> { return x + y; }
If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and not for others. The following lambda expression will not compile because it declares the type of one parameter and omits for the other:
// A compile-time error
(int x, y) -> { return x + y; }
Declaring a Single Parameter ::
Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to declare a lambda expression with a single parameter:
// Declares the parameter type
(String msg) -> { System.out.println(msg); }
// Omits the parameter type
(msg) -> { System.out.println(msg); }
// Omits the parameter type and parentheses
msg -> { System.out.println(msg); }
The parentheses can be omitted only if the single parameter also omits its type. The following lambda expression
will not compile:
// Omits parentheses, but not the parameter type, which is not allowed.
String msg -> { System.out.println(msg); }
Declaring No Parameters ::
If a lambda expression does not take any parameters, you need to use empty parentheses.
// Takes no parameters
() -> { System.out.println("Hello"); }
It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following declaration will not compile:
-> { System.out.println("Hello"); }
Parameters with Modifiers :
You can use modifiers, such as final, in the parameter declaration for explicit lambda expressions. The following two lambda expressions are valid:
(final int x, final int y) -> { return x + y; }
(int x, final int y) -> { return x + y; }
The following lambda expression will not compile because it uses the final modifier in parameter declarations,but omits the parameter type:
(final x, final y) -> { return x + y; }
Declaring Body of Lambda Expressions :
The body of a lambda expression can be a block statement or a single expression. A block statement is enclosed in braces; a single expression is not enclosed in braces.When a block statement is executed the same way as a method’s body. A return statement or the end of the body returns the control to the caller of the lambda expression.When an expression is used as the body, it is evaluated and returned to the caller. If the expression evaluates to void, nothing is returned to the caller.
The following two lambda expressions are the same; one uses a block statement and the other an expression:
// Uses a block statement. Takes two int parameters and returns their sum.
(int x, int y) -> { return x + y; }
// Uses an expression. Takes a two int parameters and returns their sum.
(int x, int y) -> x + y
The following two lambda expressions are the same; one uses a block statement as the body and the other an expression that evaluates to void:
// Uses a block statement
(String msg) -> { System.out.println(msg); }
// Uses an expression
(String msg) -> System.out.println(msg)
Commonly Used Functional Interfaces :
Java 8 has added many frequently used functional interfaces in the package java.util.function.
List of Functional Interfaces Declared in the Package java.util.function
Interface Name Method Description
Function<T,R> R apply(T t) Represents a function that takes an argument of type T
and returns a result of type R.
BiFunction<T,U,R> R apply(T t, U u) :Represents a function that takes two arguments of types T
and U, and returns a result of type R.
Predicate<T> boolean test(T t) In mathematics, a predicate is a boolean-valued function
that takes an argument and returns true or false. The function represents a condition that returns true or false for the specified argument.
BiPredicate<T,U> boolean test(T t, U u) Represents a predicate with two arguments.
Consumer<T> void accept(T t) Represents an operation that takes an argument, operates on it to produce some side effects, and returns no result.
BiConsumer<T,U> void accept(T t, U u) Represents an operation that takes two arguments,
operates on them to produce some side effects, and returns no result.
Supplier<T> T get() Represents a supplier that returns a value.
UnaryOperator<T> T apply(T t) Inherits from Function<T,T>. Represents a function that takes an argument and returns a result of the same type.
BinaryOperator<T> T apply(T t1, T t2) Inherits from BiFunction<T,T,T>. Represents a function
that takes two arguments of the same type and returns a result of the same.
Consumer functional interface:
Let take example of consumer functional interface.
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
public class GraspUtlFuncInterface {
public static void main(String[] args) {
//using java.util.function package using java8
Consumer<String> cnsmer=( s) ->display(s);
cnsmer.accept(" from consumer");
BiConsumer<String,Integer> biCnsmer=( s,a) ->displayWihtTwoargs(s,a);
biCnsmer.accept(" from biConsumer", 23);
Predicate<String> prdcate= (check)->checkStiringEmpty(check);
System.out.println(prdcate.test("from predicate"));
BiPredicate<String , Integer> biPrdcate=(a,c)->checkStiringEmpty(a, c);
System.out.println(biPrdcate.test(" from Bipredicaate", 345));
BiPredicate<Integer,Integer> expBiPrdcate=(x,y)->x>y;
BiPredicate<Integer,Integer> expOnePrdcate=(x,y)->x-2>y;
System.out.println(expBiPrdcate.and(expOnePrdcate).test(10, 5));
System.out.println(expBiPrdcate.or(expOnePrdcate).test(6,7));
IntConsumer intCnsmer=(a)->displayWihtInt(a);
intCnsmer.accept(12345);
DoubleConsumer dbCnsmer=(a)->displayWihtDble(a);
dbCnsmer.accept(123.00);
LongConsumer lngCnsmer=(a)->displayWihtLng(a);
lngCnsmer.accept(124l);
}
public static void display(String message) {
System.out.println(" dislayign messgae from ::display()" + message);
}
public static void displayWihtTwoargs(String message,int number) {
System.out.println(" dislayign messgae from ::displayWihtTwoargs()" + message + " "+number);
}
public static boolean checkStiringEmpty(String check) {
return check.length()>0?true:false;
}
public static boolean checkStiringEmpty(String check,int b) {
return check.length()>0 && b>0?true:false;
}
public static void displayWihtInt(int abc) {
System.out.println(" dislayign messgae from ::displayWihtInt()" + abc);
}
public static void displayWihtDble(double abc) {
System.out.println(" dislayign messgae from ::displayWihtDble()" + abc);
}
public static void displayWihtLng(Long abc) {
System.out.println(" dislayign messgae from ::displayWihtLng()" + abc);
}
}
Output:
What is lambda expression:
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and abody. Sometimes a lambda expression is simply called a lambda. The body of a lambda expression can be a block statement or an expression. An arrow (->) is used to separate the list of parameters and the body. The term “lambda” in "lambda expression" has its origin in Lambda calculus that uses the Greek letter lambda (l) to denote a function abstraction.
Exmaples of lambda expressions:
// Takes an int parameter and returns the parameter value incremented by 1
(int x) -> x + 1
// Takes two int parameters and returns their sum
(int x, int y) -> x + y
// Takes two int parameters and returns the maximum of the two
(int x, int y) -> { int max = x > y ? x : y;
return max;
}
// Takes no parameters and returns a string "OK"
() -> "OK"
// Takes a String parameter and prints it on the standard output
(String msg) -> { System.out.println(msg); }
// Takes a parameter and prints it on the standard output
msg -> System.out.println(msg)
// Takes a String parameter and returns its length
(String str) -> str.length()
// Takes no parameters and returns void
() -> { }
Syntax of lambda expressions::
A lambda expression describes an anonymous function. The general syntax for using lambda expressions is very similar to declaring a method.
The general syntax is (<LambdaParametersList>) -> { <LambdaBody> }
A lambda expression consists of a list of parameters and a body that are separated by an arrow (->). The list of parameters is declared the same way as the list of parameters for methods. The list of parameters is enclosed in parentheses, as is done for methods. The body of a lambda expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.
Omitting Parameter Types ::
You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in which the lambda expression is used.
// Types of parameters are declared
(int x, int y) -> { return x + y; }
// Types of parameters are omitted
(x, y) -> { return x + y; }
If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and not for others. The following lambda expression will not compile because it declares the type of one parameter and omits for the other:
// A compile-time error
(int x, y) -> { return x + y; }
Declaring a Single Parameter ::
Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to declare a lambda expression with a single parameter:
// Declares the parameter type
(String msg) -> { System.out.println(msg); }
// Omits the parameter type
(msg) -> { System.out.println(msg); }
// Omits the parameter type and parentheses
msg -> { System.out.println(msg); }
The parentheses can be omitted only if the single parameter also omits its type. The following lambda expression
will not compile:
// Omits parentheses, but not the parameter type, which is not allowed.
String msg -> { System.out.println(msg); }
Declaring No Parameters ::
If a lambda expression does not take any parameters, you need to use empty parentheses.
// Takes no parameters
() -> { System.out.println("Hello"); }
It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following declaration will not compile:
-> { System.out.println("Hello"); }
Parameters with Modifiers :
You can use modifiers, such as final, in the parameter declaration for explicit lambda expressions. The following two lambda expressions are valid:
(final int x, final int y) -> { return x + y; }
(int x, final int y) -> { return x + y; }
The following lambda expression will not compile because it uses the final modifier in parameter declarations,but omits the parameter type:
(final x, final y) -> { return x + y; }
Declaring Body of Lambda Expressions :
The body of a lambda expression can be a block statement or a single expression. A block statement is enclosed in braces; a single expression is not enclosed in braces.When a block statement is executed the same way as a method’s body. A return statement or the end of the body returns the control to the caller of the lambda expression.When an expression is used as the body, it is evaluated and returned to the caller. If the expression evaluates to void, nothing is returned to the caller.
The following two lambda expressions are the same; one uses a block statement and the other an expression:
// Uses a block statement. Takes two int parameters and returns their sum.
(int x, int y) -> { return x + y; }
// Uses an expression. Takes a two int parameters and returns their sum.
(int x, int y) -> x + y
The following two lambda expressions are the same; one uses a block statement as the body and the other an expression that evaluates to void:
// Uses a block statement
(String msg) -> { System.out.println(msg); }
// Uses an expression
(String msg) -> System.out.println(msg)
Commonly Used Functional Interfaces :
Java 8 has added many frequently used functional interfaces in the package java.util.function.
List of Functional Interfaces Declared in the Package java.util.function
Interface Name Method Description
Function<T,R> R apply(T t) Represents a function that takes an argument of type T
and returns a result of type R.
BiFunction<T,U,R> R apply(T t, U u) :Represents a function that takes two arguments of types T
and U, and returns a result of type R.
Predicate<T> boolean test(T t) In mathematics, a predicate is a boolean-valued function
that takes an argument and returns true or false. The function represents a condition that returns true or false for the specified argument.
BiPredicate<T,U> boolean test(T t, U u) Represents a predicate with two arguments.
Consumer<T> void accept(T t) Represents an operation that takes an argument, operates on it to produce some side effects, and returns no result.
BiConsumer<T,U> void accept(T t, U u) Represents an operation that takes two arguments,
operates on them to produce some side effects, and returns no result.
Supplier<T> T get() Represents a supplier that returns a value.
UnaryOperator<T> T apply(T t) Inherits from Function<T,T>. Represents a function that takes an argument and returns a result of the same type.
BinaryOperator<T> T apply(T t1, T t2) Inherits from BiFunction<T,T,T>. Represents a function
that takes two arguments of the same type and returns a result of the same.
Consumer functional interface:
Let take example of consumer functional interface.
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
public class GraspUtlFuncInterface {
public static void main(String[] args) {
//using java.util.function package using java8
Consumer<String> cnsmer=( s) ->display(s);
cnsmer.accept(" from consumer");
BiConsumer<String,Integer> biCnsmer=( s,a) ->displayWihtTwoargs(s,a);
biCnsmer.accept(" from biConsumer", 23);
Predicate<String> prdcate= (check)->checkStiringEmpty(check);
System.out.println(prdcate.test("from predicate"));
BiPredicate<String , Integer> biPrdcate=(a,c)->checkStiringEmpty(a, c);
System.out.println(biPrdcate.test(" from Bipredicaate", 345));
BiPredicate<Integer,Integer> expBiPrdcate=(x,y)->x>y;
BiPredicate<Integer,Integer> expOnePrdcate=(x,y)->x-2>y;
System.out.println(expBiPrdcate.and(expOnePrdcate).test(10, 5));
System.out.println(expBiPrdcate.or(expOnePrdcate).test(6,7));
IntConsumer intCnsmer=(a)->displayWihtInt(a);
intCnsmer.accept(12345);
DoubleConsumer dbCnsmer=(a)->displayWihtDble(a);
dbCnsmer.accept(123.00);
LongConsumer lngCnsmer=(a)->displayWihtLng(a);
lngCnsmer.accept(124l);
}
public static void display(String message) {
System.out.println(" dislayign messgae from ::display()" + message);
}
public static void displayWihtTwoargs(String message,int number) {
System.out.println(" dislayign messgae from ::displayWihtTwoargs()" + message + " "+number);
}
public static boolean checkStiringEmpty(String check) {
return check.length()>0?true:false;
}
public static boolean checkStiringEmpty(String check,int b) {
return check.length()>0 && b>0?true:false;
}
public static void displayWihtInt(int abc) {
System.out.println(" dislayign messgae from ::displayWihtInt()" + abc);
}
public static void displayWihtDble(double abc) {
System.out.println(" dislayign messgae from ::displayWihtDble()" + abc);
}
public static void displayWihtLng(Long abc) {
System.out.println(" dislayign messgae from ::displayWihtLng()" + abc);
}
}
No comments:
Post a Comment