Collectors.reducing總結

1. 方法簽名 一個引數

  1. public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op)

引數說明

  • BinaryOperator op 歸集操作函式 輸入引數T返回T

測試程式碼

我們這裡實現一個簡單的求和功能,程式碼如下

  1. //author: herbert 公眾號:小院不小 20210827
  2. @Test
  3. public void testReducingOne() {
  4. List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  5. Optional<Integer> sum = testData.stream().collect(Collectors.reducing((prev, cur) -> {
  6. System.out.println("prev=>" + prev + "cur=>" + cur);
  7. return prev + cur;
  8. }));
  9. System.out.print(sum.get()); // 45
  10. }

2. 方法簽名 兩個引數

  1. public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op)

引數說明

  • T identity 返回型別T初始值
  • BinaryOperator op 歸集操作函式 輸入引數T返回T

測試程式碼

我們這裡實現一個簡單的求和並加上20功能,程式碼如下

  1. //author: herbert 公眾號:小院不小 20210827
  2. @Test
  3. public void testReducingTwo() {
  4. List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  5. Integer sum = testData.stream().collect(Collectors.reducing(20, (prev, cur) -> {
  6. System.out.println("prev=>" + prev + "cur=>" + cur);
  7. return prev + cur;
  8. }));
  9. System.out.print(sum); //65
  10. }

2. 方法簽名 三個引數

  1. public static <T, U> Collector<T, ?, U> reducing(U identity,Function<? super T, ? extends U> mapper,BinaryOperator<U> op)

這個函式才是真正體現reducing(歸集)的過程。呼叫者要明確知道以下三個點

  1. 需要轉換型別的初始值
  2. 型別如何轉換
  3. 如何收集返回值

引數說明

  • U identity 最終返回型別U初始值
  • Function<? super T, ? extends U> mapper 將輸入引數T轉換成返回型別U的函式
  • BinaryOperator<U> op 歸集操作函式 輸入引數U返回U

測試程式碼

我們這裡實現一個簡單數字轉字串並按逗號連線的功能,程式碼如下

  1. //author: herbert 公眾號:小院不小 20210827
  2. @Test
  3. public void testReducingThree() {
  4. List<Integer> testData = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  5. String joinStr = testData.stream().collect(Collectors.reducing("轉換成字串", in -> {
  6. return in + "";
  7. }, (perv, cur) -> {
  8. return perv + "," + cur;
  9. }));
  10. System.out.print(joinStr); // 轉換成字串,1,2,3,4,5,6,7,8,9
  11. }

4. 總結

這個知識點很小,但在沒有徹底明白之前,對三個引數的呼叫特別糊塗。最主要的原因就是看到一堆 T R U 的泛型型別就不知道如何下手。歡迎大家關注我的公眾號一起收集開發中遇到的點滴知識