如何将lambda返回thenComparing方法

时间:2017-08-28 17:55:21

标签: java lambda java-8 comparator

我有一个我需要修改的代码。 它看起来像是:

new ComparatorFactory<>(thing -> thing.getLong());
return new ComparatorFactory.bySmthThenLong(things);

工厂类本身:

private final Function<T, Long> getLong;
 ComparatorFactory(Function<T, Long> getLong) {
  this.getLong = getLong;
}

Comparator<T> bySmth(Collection<T> things) {
  // Smth happens, then returns comparator. 
}

然后我需要将bySmth方法链接到另一个方法,这两个方法应该是分开的,因为有时只使用第一个阶段。 在下一轮比较之前,我需要对此Long做一些事情,所以我有一个方法:

private Function<T, Long> preprocessLong(Function<T, Long> getLong) {
 // divide Long by some number and return new function.
}

所以这个比较器的创建看起来像我的理解:

Comparator<T> bySmthThenLong(Collection<T> things) {
  return bySmth(things).thenComparing(preprocessLong(getLong));
}

但我不明白preprocessLong方法应该是什么样子。你能帮忙吗?感谢。

1 个答案:

答案 0 :(得分:3)

如果您查看JavaDoc的“函数”接口,您可以看到,使用lambda重写的方法是“apply()”方法(因为它是唯一一个抽象的方法。) 因此,您可以在新函数中调用apply,如下所示:

private Function<T, Long> preprocessLong(Function<T, Long> getLong) {
   return (thing) -> getLong.apply(thing) / someNumber;
}
相关问题