Hi Question is simple.
What is difference between String::startWith
and ""::startWith
?
Hi Question is simple.
What is difference between String::startWith
and ""::startWith
?
String::startWith
applies the startWith()
method to the first argument of the lambda.
""::startWith
applies the startWith()
method to a the ""
literal or in a broader way to a variable that is not declared as a lambda argument.
To be more exhaustive, these two ways of providing a method reference are not substitutable.
Suppose that you want to use method reference for the public boolean startsWith(String prefix)
method.
I specify it as the method is overloaded.
The method reference using a lambda parameter is designed to work with a BiPredicate<String, String>
functional interface while the method reference using a variable not declared in lambda parameters is designed to work with Predicate<String>
functional interface.
The way with a variable passed as the target of the method reference:
String myVariable;
myVariable::startWith
provides already the String on which the method reference should be applied. Here : myVariable
.
So, only the prefix parameter needs to be passed in the lambda.
So Predicate<String>
suits.
The way with using the first argument of the lambda parameter as the target of the method reference:
String::startsWith
doesn't provides the String on which the method reference should be applied.
So, both the String on which the method should be invoked and the prefix parameters need to be passed in the lambda.
So BiPredicate<String, String>
suits.
Here is a sample code to illustrate:
public static void main(String[] args) {
// using method reference with lambda parameter
myMethodWithBiPredicate((s, prefix) -> s.startsWith(prefix), "mystring", "my");
myMethodWithBiPredicate(String::startsWith, "mystring", "my");
// using method reference with variable not in lambda parameter
String stringNotInLambdaParams = "stringNotInParam";
Predicate<String> functionPredicate = stringNotInLambdaParams::startsWith;
System.out.print("myMethodWithBiPredicate with string "
+ "(included in the method reference)="
+ stringNotInLambdaParams
+ " and prefix= string | Result = ");
myMethodWithPredicate(functionPredicate, "string");
}
public static void myMethodWithBiPredicate(BiPredicate<String, String> function,
String string,
String prefix) {
System.out.println("myMethodWithBiPredicate with string="
+ string + " and prefix= " + prefix
+ " | Result = " + function.test(string, prefix));
}
public static void myMethodWithPredicate(Predicate<String> function, String prefix) {
System.out.println(function.test(prefix));
}
that produces this output :
myMethodWithBiPredicate with string=mystring and prefix= my | Result = true
myMethodWithBiPredicate with string=mystring and prefix= my | Result = true
myMethodWithPredicate with string (included in the method reference)=stringNotInParam and prefix= string | Result = true