2017-08-28 16 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

謝謝,這很有道理! –