New Feature of Java 8: Method reference of Lambda expressions (supplementary version of Lambda expressions) -- Nono "graffiti" memory
Method reference
1. Method reference
Method reference is used to directly reference the existing methods or constructor methods of the category class or instance. Method reference provides a way to reference without executing a method. It requires a target type context consisting of compatible functional interfaces. During calculation, a method reference creates an instance of a function interface.
When a Lambda expression only executes a method call, it does not need a Lambda expression and is more readable directly in the form of method reference. Method reference is a more concise and easy-to-understand Lambda expression.
2. Role
The only purpose of method reference is to support the shorthand for Lambda.
Method reference improves code readability and makes the logic clearer. (Advantage)
3. Composition
Use the: operator to separate the method name from the object or class name.
":" Is a domain operator (also known as delimiters and delimiters ).
Eg:
4. Category
1) Static Method reference
Syntax format: ClassName: staticMethodName
Note:
Static Method reference is easier to understand. Compared with static method calls, you can simply replace. With: static method reference can be used wherever the target type is compatible.
Eg:
-- String: valueOf is equivalent to lambda expression (s)-> String. valueOf (s)
-- Math: pow is equivalent to lambda expressions (x, y)-> Math. pow (x, y );
-- Assume that you need to find the largest number from a number list.
Method reference:
(Max is a static method in Collections. It needs to input a List parameter .)
Function, Integer> maxFn = Collections: max;
MaxFn. apply (Arrays. asList (1, 10, 3, 5 )).
The above is equivalent to the Lambda expression Function, Integer> maxFn = (numbers)-> Collections. max (numbers );.
-- Take string inversion as an example:
/** Function interface **/interface StringFunc {String func (String n);} class MyStringOps {// static method: reverse the String public static String strReverse (String str) {String result = ""; for (int I = str. length ()-1; I> = 0; I --) {result + = str. charAt (I) ;}return result ;}} class MethodRefDemo {public static String stringOp (StringFunc sf, String s) {return sf. func (s);} public static void main (String [] args) {String inStr = "lambda add power to Java"; // MyStringOps :: strReverse implements the interface method func (), and MyStringOps is implemented in the interface method func. strReverse () operation String outStr = stringOp (MyStringOps: strReverse, inStr); System. out. println ("Original string:" + inStr); System. out. println ("String reserved:" + outStr );}}
Output result:
Original string: lambda add power to Java
String reserved: avaJ ot rewop dda adbmal
Analysis:
In the program, pay special attention to the following line of code: String outStr = stringOp (MyStringOps: strReverse, inStr );
The reference to the static method strReverse () declared in MyStringOps is passed to the first parameter of the stringOp () method. This can be done because
StrReverse is compatible with StringFunc functional interfaces. Therefore, the calculation result of the expression MyStringOps: strReverse is an object reference,
StrReverse provides the implementation of the StringFunc func () method.
-- Find the object with the maximum value in the list
(One way to find the maximum element in the set is to use the max () method defined by the Collections class. For the max () version used here, you must pass a set reference and an instance of the object that implements the Comparator interface. The Comparator interface specifies how to compare two objects. It only defines the abstract method compare (). This method accepts two parameters, whose types are the types of objects to be compared. If the first parameter is greater than the second parameter, this method returns a positive number. If the two parameters are equal, 0 is returned. If the first parameter is smaller than the second parameter, a negative number is returned.
In the past, to use user-defined objects in the max () method, you must first explicitly implement the Comparator interface through a class, and then create an instance of the class, use this method to obtain an instance of the Comparator interface, and then pass the instance as a Comparator to the max () method. In JDK 8, the reference of the comparison method can now be passed to the max () method, because this will automatically implement the comparator .)
Class MyClass {private int val; MyClass (int v) {val = v;} public int getValue () {return val ;}} class UseMethodRef {public static int compareMC (MyClass, myClass B) {return. getValue ()-B. getValue () ;}public static void main (String [] args) {ArrayList a1 = new ArrayList (); a1.add (new MyClass (1 )); a1.add (new MyClass (4); a1.add (new MyClass (2); a1.add (new MyClass (9); a1.add (new MyClass (3); a1.add (new mycia Ss (7); // UseMethodRef: compareMC generates an instance of the compare () method defined by the abstract interface Comparator. MyClass maxValObj = Collections. max (a1, UseMethodRef: compareMC); System. out. println ("Maximum value is:" + maxValObj. getValue ());}}
Output result:
Maximum value is: 9
Analysis:
In the program, note that MyClass does not define its own comparison method and does not implement the Comparator interface. However, you can still obtain the maximum value in the MyClass Object List by calling the max () method, because UseMethodRef defines the static method compareMC (), which is compatible with the compare () method defined by Comparator. Therefore, it is not necessary to explicitly implement the Comparator interface and create its instance.
2) instance method reference
This syntax is similar to the syntax used for static methods, except that object references are used instead of class names.
There are three types of instance method reference:
A. instance method reference on the instance
Syntax format: instanceReference: methodName
Note:
For instance method reference of a specific (or any) object, add a separator between the instance method name and its type name:
Compared with reference to static method reference, they are all replaced with instance objects.
Eg:
-- Function upper = String: toUpperCase; --/** Function interface **/interface StringFunc {String func (String n);} class MyStringOps {// common method: reverse String public String strReverse (String str) {String result = ""; for (int I = str. length ()-1; I> = 0; I --) {result + = str. charAt (I) ;}return result ;}} class MethodRefDemo2 {public static String stringOp (StringFunc sf, String s) {return sf. func (s);} public static void main (String [] args) {String inStr = "lambda add power to Java"; MyStringOps strOps = new MyStringOps (); // Instance Object // MyStringOps: strReverse is equivalent to implementing the interface method func (), and MyStringOps is implemented in the interface method func. strReverse () operation String outStr = stringOp (strOps: strReverse, inStr); System. out. println ("Original string:" + inStr); System. out. println ("String reserved:" + outStr );}}
Output result:
Original string: lambda add power to Java
String reserved: avaJ ot rewop dda adbmal
Analysis:
The class name is used here, rather than the specific object, although the instance method is specified. In this form, the first parameter of the function interface matches the called object, and the second parameter matches the parameter specified by the method.
-- A counter () method is defined to count the number of objects that meet the conditions defined by the fun () method of the functional interface MyFunc in an array. In this example, count the number of instances of the HighTemp class.
Interface MyFunc {boolean func (T v1, T v2);} class HighTemp {private int hTemp; HighTemp (int ht) {hTemp = ht;} public boolean sameTemp (HighTemp ht2) {return hTemp = ht2.hTemp;} public boolean lessThanTemp (HighTemp ht2) {return hTemp
Output result:
3 days had a high of 89
2 days had a high of 12
3 days had a high less than 89
5 days had a hign less than 19
Analysis:
Note that HighTemp has two instance methods: someTemp () and lessThanTemp (). If two HighTemp objects contain the same temperature, the sameTemp () method returns true. If the temperature of the called object is less than the temperature of the passed object, the lessThanTemp () method returns true. Both methods have a HighTemp parameter and return a boolean result. Therefore, both methods are compatible with the MyFunc function interface, because the called object type can be mapped to the first parameter of func (), and the passed real parameters can be mapped to func (). Therefore, this expression: HighTemp: sameTemp
When the counter () method is passed, an instance of the function interface is created. The parameter type of the first parameter is the type of the object called by the instance method, that is, HighTemp. The type of the second parameter is also HighTemp, because it is a parameter of the sameTemp () method. This is also true for lessThanTemp.
Note:
In the above program, the function boolean func (T v1, T v2) in the function interface contains two parameters, while the sameTemp (HighTemp ht2) function in HighTemp contains one parameter, but the reason for compatibility is:
In fact, the sameTemp (HighTemp ht2) in the HighTemp class actually contains two parameters. By default, this is a reference to call this function.
Therefore, when the instance method of the class is used as the method reference, the first parameter of the function interface matches the call object of the instance method of the class, and the second parameter matches the parameter specified by the method.
B. instance method reference on the superclass
Syntax format: super: methodName
The method name is specified by methodName.
By using super, You can reference the superclass version of the method.
Eg: super: name
Note: this pointer can also be captured.
This: equals is equivalent to lambda expression x-> this. equals (x );
C. instance method reference on the Type
Syntax format: ClassName: methodName
Note:
If the type of the instance method is generic, you need to provide the type parameter before: separator, or (in most cases) use the target type to export its type.
Static Method reference and instance method reference on the type have the same syntax. The compiler makes a decision based on the actual situation.
Generally, we do not need to specify the parameter type in the method reference, because the compiler can usually export the result, but we can also explicitly provide the parameter type information before: separator.
Eg:
String: toString is equivalent to lambda expressions (s)-> s. toString ()
It is not easy to understand here. The instance method should be called through an object. The method reference corresponds to Lambda, and the first parameter of Lambda will become the object for calling the instance method.
You can also use method references in generic or generic methods.
interface MyFunc {int func(T[] als, T v);}class MyArrayOps {public static int countMatching(T[] vals, T v) {int count = 0;for (int i = 0; i < vals.length; i++) {if (vals[i] == v) count++;}return count;}}class GenericMethodRefDemo {public static int myOp(MyFunc f, T[] vals, T v) {return f.func(vals, v);}public static void main(String[] args){Integer[] vals = {1, 2, 3, 4, 2, 3, 4, 4, 5};String[] strs = {"One", "Two", "Three", "Two"};int count;count=myOp(MyArrayOps::countMatching, vals, 4);System.out.println("vals contains "+count+" 4s");count=myOp(MyArrayOps::countMatching, strs, "Two");System.out.println("strs contains "+count+" Twos");}}
Output result:
Vals contains 3 4S
Strs contains 2 Twos
Analysis:
In the program, MyArrayOps is a non-generic class and contains the generic method countMatching (). This method returns the number of elements in the array that match the specified value. Note how to specify generic parameters here. For example, in the main () method, the first call to the countMatching () method is as follows: count = myOp (MyArrayOps: countMatching, vals, 4 );
The type parameter Integer is passed here.
Note that the parameter is passed after. This syntax can be promoted. When a generic method is specified as a method reference, the type parameter appears after: And before the method name. However, it should be noted that in this case (and many other cases), it is not necessary to display the specified type parameter, because the type parameter will be automatically inferred. If you specify a generic class, the type parameter is located after the class name.
3) constructor reference
Constructor references are divided into constructor references and array constructor references.
A. constructor reference)
Syntax format: Class: new
The constructor is essentially a static method, but the method name is special and uses the new keyword.
Eg:
-- String: new, equivalent to lambda expression ()-> new String () -- List strings = new ArrayList (); strings. add ("a"); strings. add ("B"); Stream stream = strings. stream (). map (Button: new); List buttons = stream. collect (Collectors. toList (); -- the reference interface MyFunc {MyClass func (int n) can be referenced by any function interface that is compatible with the constructor );} class MyClass {private int val; MyClass (int v) {val = v;} MyClass () {val = 0;} public int getValue () {return val ;}} class ConstructorRefDemo {public static void main (String [] args) {MyFunc myClassCons = MyClass: new; MyClass mc = myClassCons. func (100); System. out. println ("val in mc is:" + mc. getValue ());}}
Output result:
Val in mc is: 100
B. array constructor reference:
Syntax format: TypeName []: new
Eg:
-- Int []: new is a constructor reference that contains a parameter. this parameter is the length of the array.
It is equivalent to lambda expression x-> new int [x].
-- Assume that an array constructor receives the int parameter.
IntFunction arrayMaker = int []: new;
Int [] array = arrayMaker. apply (10) // create an array int [10]