Collectors.reducing總結
1. 方法簽名 一個參數
public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op)
參數說明
- BinaryOperator
op 歸集操作函數 輸入參數T返回T
測試代碼
我們這里實現一個簡單的求和功能,代碼如下
//author: herbert 公眾號:小院不小 20210827
@Test
public void testReducingOne() {
List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Optional<Integer> sum = testData.stream().collect(Collectors.reducing((prev, cur) -> {
System.out.println("prev=>" + prev + "cur=>" + cur);
return prev + cur;
}));
System.out.print(sum.get()); // 45
}
2. 方法簽名 兩個參數
public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op)
參數說明
- T identity 返回類型T初始值
- BinaryOperator
op 歸集操作函數 輸入參數T返回T
測試代碼
我們這里實現一個簡單的求和並加上20功能,代碼如下
//author: herbert 公眾號:小院不小 20210827
@Test
public void testReducingTwo() {
List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Integer sum = testData.stream().collect(Collectors.reducing(20, (prev, cur) -> {
System.out.println("prev=>" + prev + "cur=>" + cur);
return prev + cur;
}));
System.out.print(sum); //65
}
2. 方法簽名 三個參數
public static <T, U> Collector<T, ?, U> reducing(U identity,Function<? super T, ? extends U> mapper,BinaryOperator<U> op)
這個函數才是真正體現reducing(歸集)的過程。調用者要明確知道以下三個點
- 需要轉換類型的初始值
- 類型如何轉換
- 如何收集返回值
參數說明
- U identity 最終返回類型U初始值
- Function<? super T, ? extends U> mapper 將輸入參數T轉換成返回類型U的函數
- BinaryOperator<U> op 歸集操作函數 輸入參數U返回U
測試代碼
我們這里實現一個簡單數字轉字符串並按逗號連接的功能,代碼如下
//author: herbert 公眾號:小院不小 20210827
@Test
public void testReducingThree() {
List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
String joinStr = testData.stream().collect(Collectors.reducing("轉換成字符串", in -> {
return in + "";
}, (perv, cur) -> {
return perv + "," + cur;
}));
System.out.print(joinStr); // 轉換成字符串,1,2,3,4,5,6,7,8,9
}
4. 總結
這個知識點很小,但在沒有徹底明白之前,對三個參數的調用特別糊塗。最主要的原因就是看到一堆 T R U 的泛型類型就不知道如何下手。歡迎大家關注我的公眾號一起收集開發中遇到的點滴知識