Last active
June 26, 2021 03:40
-
-
Save wkdalsgh192/25a7f58a983fd8dfe85c151affd32ce0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.BinaryOperator; | |
public class MethodReferencesExamples { | |
public static <T> T mergeThings(T a, T b, BinaryOperator<T> merger) { | |
return merger.apply(a, b); | |
} | |
public static String appendStrings(String a, String b) {return a+b;} | |
public String appendStrings2(String a, String b) {return a+b;} | |
public static void main(String[] args) { | |
// Calling the method mergeThings with a lambda expression | |
System.out.println(MethodReferencesExamples.mergeThings("Hello ", "World", (a,b) -> a+b)); | |
// Reference to a static method | |
System.out.println(MethodReferencesExamples.mergeThings("Hello ", "World", MethodReferencesExamples::appendStrings)); | |
// Reference to an instance method of a particular object | |
MethodReferencesExamples myApp = new MethodReferencesExamples(); | |
System.out.println(MethodReferencesExamples.mergeThings("Hello ", "World", myApp::appendStrings2)); | |
// Reference to an instance method of an arbitrary object of a particular type | |
System.out.println(MethodReferencesExamples.mergeThings("Hello ", "World", String::concat)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment