I have not seen any atomic & accessible illustrations of the use of method reference operator (::) in Java.
The method reference operator (::) is a shorthand which tells the Java JVM to pass parameters automatically to a method.
If your lambda expression is like this:
str -> System.out.println(str)
then you can replace it with a method reference like this:
System.out::println
The above is a simple example with simpler & easier examples and instances to follow
The way the following illustrations work is so: first we will illustrate the straightforward way of doing it and then we will illustrate the same thing using the reference method operator (::).Method reference to a static method of a class
Following illustrates passing parameters to a static method:
[BEGIN CODE] [/END CODE]
The print out from the above code is:
Line 8 above goes over the straightforward implementation of taking an arraylist & going over its elements and printing them out. Line 8 says : take an element of the messages arraylist as the str variable (short for string) and print out the string variable str. Then Line 9 does the same thing as line 8 but using the method reference (::) operator. All the rest of the examples will follow the same pattern.
Method reference to an instance method of an object
The source code would be:
[BEGIN CODE] [/BEGIN CODE]The output from the above source code would be:
As you may observe from above (line 19) illustrates the use of the instance method of a String object (alpha) , the instance method being startsWith. Line 19 illustrates the straightforward implementation (without using the method reference operator ::) . In contast Line 23 illustrates the use of the method reference operator (::).
Method reference to an instance method of an instance to be determined at runtime
The source code would be:
[BEGIN CODE] [/BEGIN CODE]The out put from the source code above would be:
As you may observe from above (line 17) illustrates the use of the instance method of a String object (txt) , the instance method being isEmpty. Although Line 17 illustrates the use of a straighforward lambda expression line 19 illustrates the employment of the refrence method operator (::).
Method reference to the constructor of a Class
The source code would be:
[BEGIN CODE] [/BEGIN CODE]The out put from the source code above would be:
As you may observe from above (line 7) illustrates the use of the constructor of an Example object . Although Line 7 illustrates the use of a straighforward lambda expression line 8 illustrates the employment of the refrence method operator (::).
No comments:
Post a Comment