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 的泛型型別就不知道如何下手。歡迎大家關注我的公眾號一起收集開發中遇到的點滴知識