Use of double colons - difference between static and non-static method references [duplicate]

浪子不回头ぞ 提交于 2019-12-05 05:37:52
Averager averageCollect = zahlen.stream()
  .collect(Averager::new, Averager::addcount, Averager::combine);

This is fine. It is equivalent to

Averager averageCollect = zahlen.stream()
  .collect(() -> new Averager(),
           (myAverager, n) -> myAverager.addcount(n),
           (dst, src) -> dst.combine(src))

Remember every nonstatic method has a hidden this parameter. In this case it is (correctly) binding this to the first argument of the accumulator and combiner callbacks.

It will also work with static methods such as:

public static void addcount(Averager a, int i) {
    a.total += i;
    a.count++;
}
public static void combine(Averager dst, Averager src) {
    dst.total += src.total;
    dst.count += src.count;
}

which hopefully makes it clearer what is happening.

But there is no need to change the code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!