Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer::toString in Optional.map

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.

like image 638
X.Hu Avatar asked Jan 23 '19 09:01

X.Hu


People also ask

What is the use of integer toString () in Java?

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.

How do you change a string from optional to string?

In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .

What is the difference between string valueOf and integer toString?

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).


1 Answers

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?

like image 53
Eugene Avatar answered Oct 08 '22 16:10

Eugene