2017-08-28 20 views
1

我有一个代码,我需要修改。 它看起来像这样:如何返回lambda到thenComparing方法

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方法应该看起来像什么。你能帮忙吗?谢谢。

回答

3

如果你看看JavaDoc的“函数”接口,你可以看到,你用lambda覆盖的方法是“apply()”方法(因为它是唯一一个抽象的)。 所以你可以这样称呼你的新功能:

private Function<T, Long> preprocessLong(Function<T, Long> getLong) { 
    return (thing) -> getLong.apply(thing)/someNumber; 
} 
+0

看起来像这样的作品,谢谢。如果我有一个条件,所以'返回条件? (thing) - > getLong.apply(thing)/ someNumber:0;'如果不是true则返回0,这里怎么做? –

+1

'return(thing) - >(condition)? getLong.apply(thing)/ someNumber:0;' – feldim2425

+0

谢谢,这很有道理! –