Java Stream 函數式介面外部實例的引用

Java Function Interface 函數式介面:
Stream.empty()
.filter(Predicate)
.map(Function)
.forEach(Consumer);

每處調用持有唯一 Function Interface 實例,Function Interface 對象可持有外部「不可變」對象。
進而將外部對象嵌入Stream操作中,藉以完成一些功能。

如:創建用於去重的Predicate
public static <T, R> Predicate<T> distinctByKey(Function<T, R> keyExtractor) {
// 創建對象map
ConcurrentHashMap<R, Boolean> map = new ConcurrentHashMap<>();
// 返回一個Predicate對象實例
return t ->
// 持有外部map引用
map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE)
// 不存在的返回V為NULL
== null;
}
該方法雖然在調用結束後結束了生命周期,但map引用被到了Stream的生命周期,直到Stream終端操作調用結束後釋放。

諸如此類功能可以進行多種擴展,如:

.map dao -> vo or mapper 添加依賴其它對象的屬性

注意:外部引用對象要考慮是否多執行緒安全!

Tags: