When using map with method reference in Java, I met following problem:
public class Dummy {
public static void main(String[] args) {
IntegerHolder ih = new IntegerHolder();
Optional<IntegerHolder> iho = Optional.of(ih);
iho.map(IntegerHolder::getInteger).map(Objects::toString);
iho.map(IntegerHolder::getInteger).map((Integer ii) ->ii.toString());
iho.map(IntegerHolder::getInteger).map(Integer::toString);// this line will not compile. The error is "non-static method toString() cannot be referenced from a static context"
}
private static class IntegerHolder {
private Integer i;
Integer getInteger() {return i;}
}
}
It looks to me that Integer::toString is same as the IntegerHolder::getInteger. Both are "Reference to an Instance Method of an Arbitrary Object of a Particular Type" I do not understand why one works, but the other does not. Could you please shed some light on this question? Thank you very much.
toString() is an inbuilt method in Java which is used to return the String object representing this Integer's value. Parameters: The method does not accept any parameters. Return Value:The method returns the string object of the particular Integer value.
In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
You will clearly see that String. valueOf(int) is simply calling Integer. toString(int) for you. Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object).
The error is very misleading, in java-11 for example the error would make a lot more sense:
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer match)
If you re-write this method via a lambda expression, you will see that both signatures can potentially match:
iho.map(IntegerHolder::getInteger).map((Integer ii) -> Integer.toString(ii));
iho.map(IntegerHolder::getInteger).map((Integer ii) -> ii.toString());
both of these can be re-written as a method reference, but in such a case, which method to call?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With