欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java8 Collectors求和功能的自定義擴展操作

 更新時間:2021年02月24日 16:04:10   作者:Jaemon  
這篇文章主要介紹了Java8 Collectors求和功能的自定義擴展操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

業(yè)務中需要將一組數(shù)據(jù)分類后收集總和,原本可以使用Collectors.summingInt(),但是我們的數(shù)據(jù)源是BigDecimal類型的,而Java8原生只提供了summingInt、summingLong、summingDouble三種基礎(chǔ)類型的方法。

于是就自己動手豐衣足食吧。。

自定義工具類

public class MyCollectors {
  private MyCollectors() {
  }
//  public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(Function<? super T, BigDecimal> mapper) {}
 	// BigDecimal 類型的集合求和
  public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(ToBigDecimalFunction<? super T> mapper) {
    return new CollectorImpl<>(
        () -> new BigDecimal[] { BigDecimal.ZERO },
        (a, t) -> a[0] = a[0].add(mapper.applyAsInt(t)),
        (a, b) -> {
          a[0] = a[0].add(b[0]);
          return a;
        },
        a -> a[0],
        Collections.emptySet()
    );
  }
  static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
    // 創(chuàng)建一個計算用的容器
    private final Supplier<A> supplier;
    // 計算邏輯
    private final BiConsumer<A, T> accumulator;
    // 合并邏輯
    private final BinaryOperator<A> combiner;
    // 返回最終計算值
    private final Function<A, R> finisher;
    // 空Set
    private final Set<Characteristics> characteristics;
    CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
           Function<A, R> finisher, Set<Characteristics> characteristics) {
      this.supplier = supplier;
      this.accumulator = accumulator;
      this.combiner = combiner;
      this.finisher = finisher;
      this.characteristics = characteristics;
    }
    CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
           Set<Characteristics> characteristics) {
      this(supplier, accumulator, combiner, castingIdentity(), characteristics);
    }
    @Override
    public BiConsumer<A, T> accumulator() {
      return accumulator;
    }
    @Override
    public Supplier<A> supplier() {
      return supplier;
    }
    @Override
    public BinaryOperator<A> combiner() {
      return combiner;
    }
    @Override
    public Function<A, R> finisher() {
      return finisher;
    }
    @Override
    public Set<Characteristics> characteristics() {
      return characteristics;
    }
  }
  @SuppressWarnings("unchecked")
  private static <I, R> Function<I, R> castingIdentity() {
    return i -> (R) i;
  }
}

自定義函數(shù)式接口

@FunctionalInterface
public interface ToBigDecimalFunction<T> {
  BigDecimal applyAsInt(T value);
}

測試入口

public class AnswerApp {
 public static void main(String[] args) {
    List<BigDecimal> list = Lists.newArrayList();
    for (int i = 0; i < 24; i++) {
      list.add(BigDecimal.valueOf(i + 10.2121543));
    }
    // 方式1
    BigDecimal sum = list.stream().collect(MyCollectors.summingBigDecimal(e -> e));
    System.out.println(sum.doubleValue());
    // 方式2
    Optional<BigDecimal> reduce = list.stream().reduce(BigDecimal::add);
    System.out.println(reduce.orElse(BigDecimal.valueOf(0)));
 }    
}
// OUTPUT: 521.0917032

補充:Collectors擴展接口 實現(xiàn)BigDecimal的相加

第一步

創(chuàng)建ToBigDecimalFunction接口

import java.math.BigDecimal;
@FunctionalInterface
public interface ToBigDecimalFunction<T> {
  BigDecimal applyAsBigDecimal(T value);
}

第二步

創(chuàng)建工具類 實現(xiàn)接口

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class CollectorsUtil {
  static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
  private CollectorsUtil() {
  }
  @SuppressWarnings("unchecked")
  private static <I, R> Function<I, R> castingIdentity() {
    return i -> (R) i;
  }
  /**
   * Simple implementation class for {@code Collector}.
   *
   * @param <T>
   *      the type of elements to be collected
   * @param <R>
   *      the type of the result
   */
  static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
    private final Supplier<A> supplier;
    private final BiConsumer<A, T> accumulator;
    private final BinaryOperator<A> combiner;
    private final Function<A, R> finisher;
    private final Set<Characteristics> characteristics;
    CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
           Function<A, R> finisher, Set<Characteristics> characteristics) {
      this.supplier = supplier;
      this.accumulator = accumulator;
      this.combiner = combiner;
      this.finisher = finisher;
      this.characteristics = characteristics;
    }
    CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
           Set<Characteristics> characteristics) {
      this(supplier, accumulator, combiner, castingIdentity(), characteristics);
    }
    @Override
    public BiConsumer<A, T> accumulator() {
      return accumulator;
    }
    @Override
    public Supplier<A> supplier() {
      return supplier;
    }
    @Override
    public BinaryOperator<A> combiner() {
      return combiner;
    }
    @Override
    public Function<A, R> finisher() {
      return finisher;
    }
    @Override
    public Set<Characteristics> characteristics() {
      return characteristics;
    }
  }
  public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(ToBigDecimalFunction<? super T> mapper) {
    return new CollectorImpl<>(() -> new BigDecimal[1], (a, t) -> {
      if (a[0] == null) {
        a[0] = BigDecimal.ZERO;
      }
      a[0] = a[0].add(mapper.applyAsBigDecimal(t));
    }, (a, b) -> {
      a[0] = a[0].add(b[0]);
      return a;
    }, a -> a[0], CH_NOID);
  }
}

使用測試

import com.example.javademo.JavaDemoApplicationTests;
import com.example.javademo.pojo.Student;
import com.example.javademo.utils.DataUtils;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.stream.Collectors;
public class TestBigDecimal extends JavaDemoApplicationTests {
  @Test
  public void testGroupByAfterBigdecimal(){
    /*
    自定義實現(xiàn)對分組后的集合,屬性為bigdecmal進行相加
     */
    System.out.println(DataUtils.getData().stream().collect(Collectors.groupingBy(Student::getSchool,CollectorsUtil.summingBigDecimal(Student::getMoney))));
    //歸約造作
    BigDecimal reduce = DataUtils.getData().stream().map(Student::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println(reduce);
    int sum = DataUtils.getData().stream().mapToInt(Student::getAge).sum();
    System.out.println(sum);
  }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • 在Map中實現(xiàn)key唯一不重復操作

    在Map中實現(xiàn)key唯一不重復操作

    這篇文章主要介紹了在Map中實現(xiàn)key唯一不重復操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Mybatis 查詢語句條件為枚舉類型時報錯的解決

    Mybatis 查詢語句條件為枚舉類型時報錯的解決

    這篇文章主要介紹了Mybatis 查詢語句條件為枚舉類型時報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java實現(xiàn)線程通信的案例講解

    Java實現(xiàn)線程通信的案例講解

    所謂線程通信就是線程間相互發(fā)送數(shù)據(jù),線程通信通常通過共享一個數(shù)據(jù)的方式實現(xiàn)。本文將通過案例詳解Java中線程通信的實現(xiàn),感興趣的可以了解一下
    2022-05-05
  • springboot整合JavaCV實現(xiàn)視頻截取第N幀并保存圖片

    springboot整合JavaCV實現(xiàn)視頻截取第N幀并保存圖片

    這篇文章主要為大家詳細介紹了springboot如何整合JavaCV實現(xiàn)視頻截取第N幀并保存為圖片,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-08-08
  • 實例分析java對象中淺克隆和深克隆

    實例分析java對象中淺克隆和深克隆

    在本篇文章中我們給大家分享了關(guān)于java對象中淺克隆和深克隆的相關(guān)知識點和相關(guān)代碼內(nèi)容,有興趣的朋友們學習下。
    2018-10-10
  • Java字段初始化的規(guī)律解析

    Java字段初始化的規(guī)律解析

    這篇文章主要介紹了Java字段初始化的規(guī)律解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-10-10
  • Java移除無效括號的方法實現(xiàn)

    Java移除無效括號的方法實現(xiàn)

    本文主要介紹了Java移除無效括號的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn)

    SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn)

    本文主要介紹了SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn),包括了手動創(chuàng)建DTO、使用ModelMapper和Lombok創(chuàng)建DTO的示例,具有一定的參考價值,感興趣的可以了解一下
    2024-07-07
  • 詳解JAVA 原型模式

    詳解JAVA 原型模式

    這篇文章主要介紹了JAVA 原型模式的的相關(guān)資料,文中講解非常細致,實例幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-06-06
  • Intellij IDEA Debug調(diào)試技巧(小結(jié))

    Intellij IDEA Debug調(diào)試技巧(小結(jié))

    這篇文章主要介紹了Intellij IDEA Debug調(diào)試技巧(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10

最新評論