java可选接口方法:不明确的方法引用

dxxyhpgq  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(460)

这个问题在这里已经有答案了

如何修复方法引用的不明确类型(整数的字符串)(3个答案)
一年前关门了。
我已经把它编码了:

this.referenceService.get(id)
    .map(Reference::hashCode)
    .map(Integer::toString);

我得到这个编译错误:
不明确的方法引用:integer类型的tostring()和tostring(int)都是合格的
我怎样才能解决这个问题?

dsekswqp

dsekswqp1#

您有两种可能的解决方案:
替换为lambda:

this.referenceService.get(id)
    .map(ref-> Integer.toString(ref.hashCode()));

使用objects.tostring()

this.referenceService.get(id)
    .map(Reference::hashCode)
    .map(Objects::toString); // this will cal toString method on you hash

编写自己的方法:

this.referenceService.get(id)
    .map(this::toHashString);

private Strign toHashString(Reference ref) {
  return Integer.toString(ref.hashCode());
}

相关问题