Toby Toby - 1 year ago 94
Java Question

How to fix ambiguous type on Java8 method reference (toString of an Integer)

When doing this

Stream.of(1, 32, 12, 15, 23).map(Integer::toString);

I get an ambiguous type error. Understandably, the compiler can't tell if I mean

When not using a method reference, I might have gotten out of this with an explicit cast or write out the generics long hand, but how can I let the compiler know what I mean here? What syntax (if any) can I use to make in unambiguous?

Answer Source

There is no way to make method references unambiguous; simply said, method references are a feature that is just supported for unambiguous method references only. So you have two solutions:

  1. use a lambda expression:

    Stream.of(1, 32, 12, 15, 23).map(i->Integer.toString(i));
  2. (preferred, at least by me) Use a stream of primitive int values when the source consists of primitive int values only:

    IntStream.of(1, 32, 12, 15, 23).mapToObj(Integer::toString);

    This will use the static Integer.toString(int) method for consuming the int values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download