java constructor lambda code example
Example 1: java method reference
Java provides a feature called method
reference in Java 8. Method reference
is used to refer method of functional interface.
It is compact and easy form
of lambda expression. Each time when
you are using lambda expression to just
referring a method, you can replace your
lambda expression with method reference.
Types of Method References:
- Reference to a static method. Syntax ==> ContainingClass::staticMethodName
- Reference to an instance method. Syntax ==> containingObject::instanceMethodName
- Reference to a constructor. Syntax ==> ClassName::new
Example 2: lambda expressions in java
A lambda expression is a short block
of code which takes in parameters
and returns a value. Lambda expressions
are similar to methods, but they do
not need a name and they can be
implemented right in the body of a method.
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Example
Use a lamba expression in the ArrayList's
forEach() method to print every item in the list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}