Collection API:-
Stream API:-
Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.
Stream<String> stream = Stream.empty(); stream.forEach(System.out::println);
ContainingClass::staticMethodName
containingObject::instanceMethodName
ContainingType::methodName
ClassName::new
Method reference is used to refer method of the functional interface. It is a compact and easy form of a lambda expression. Each time when you are using a lambda expression to just referring a method, you can replace your lambda expression with a method reference.
Below are a few examples of method reference:
(o) -> o.toString();
can become:
Object::toString();
Static method reference:
String::valueOf;
Bound instance method reference:
str::toString;
Unbound instance method reference:
String::toString;
@FunctionalInterface interface Sayable{ void say(String msg); // abstract method } Let's demonstrate a custom functional interface via the main() method.
public class FunctionalInterfacesExample { public static void main(String[] args) { Sayable sayable = (msg) -> { System.out.println(msg); }; sayable.say("Say something .."); } }
interface Printable { void print(String msg); } public class JLEExampleSingleParameter { public static void main(String[] args) { // with lambda expression Printable withLambda = (msg) -> System.out.println(msg); withLambda.print(" Print message to console...."); } } output:
Print message to console....
Java Lambda Expression Syntax:
(argument-list) -> {body}
For example, Consider we have a functional interface:
interface Addable{ int add(int a,int b); } Let's implement the above Addable functional interface using a lambda expression:
Addable withLambdaD = (int a,int b) -> (a+b); System.out.println(withLambdaD.add(100,200));