Skip to content

Instantly share code, notes, and snippets.

@wkdalsgh192
Last active June 26, 2021 03:40
Show Gist options
  • Save wkdalsgh192/25a7f58a983fd8dfe85c151affd32ce0 to your computer and use it in GitHub Desktop.
Save wkdalsgh192/25a7f58a983fd8dfe85c151affd32ce0 to your computer and use it in GitHub Desktop.
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