Java Reference
In-Depth Information
forEach() method. This method takes a Consumer function. Then each item is passed to this function. The function
can take any action on the item. You passed a Consumer that prints the item on the standard output as shown:
FunctionUtil.forEach(list, p -> System.out.println(p) );
Typically, a Consumer applies an action on the item it receives to produce side effects. In this case, it simply prints
the item, without producing any side effects.
Method References
A lambda expression represents an anonymous function that is treated as an instance of a functional interface.
A method reference is shorthand to create a lambda expression using an existing method. Using method references
makes your lambda expressions more readable and concise; it also lets you use the existing methods. If a lambda
expression contains a body that is an expression using a method call, you can use a method reference in place of that
lambda expression.
a method reference is not a new type in Java. it is not a function pointer as used in some other programming
languages. it is simply shorthand for writing a lambda expression using an existing method. it can only be used where a
lambda expression can be used.
Tip
Let's consider an example before I explain the syntax for method references. Consider the following snippet of code:
import java.util.function.ToIntFunction;
...
ToIntFunction<String> lengthFunction = str -> str.length() ;
String name = "Ellen";
int len = lengthFunction.applyAsInt(name);
System.out.println("Name = " + name + ", length = " + len);
Name = Ellen, length = 5
The code uses a lambda expression to define an anonymous function that takes a String as an argument and
returns its length. The body of the lambda expression consists of only one method call that is the length() method of
the String class. You can rewrite the above lambda expression using a method reference to the length() method of
the String class, as shown:
import java.util.function.ToIntFunction;
...
ToIntFunction<String> lengthFunction = String::length ;
String name = "Ellen";
int len = lengthFunction.applyAsInt(name);
System.out.println("Name = " + name + ", length = " + len);
Name = Ellen, length = 5
 
 
Search WWH ::




Custom Search