Java8 Collectors求和功能的自定義擴展操作
業務中需要將一組數據分類後收集總和,原本可以使用Collectors.summingInt(),但是我們的數據源是BigDecimal類型的,而Java8原生隻提供瞭summingInt、summingLong、summingDouble三種基礎類型的方法。
於是就自己動手豐衣足食吧。。
自定義工具類
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> { // 創建一個計算用的容器 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; } }
自定義函數式接口
@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擴展接口 實現BigDecimal的相加
第一步
創建ToBigDecimalFunction接口
import java.math.BigDecimal; @FunctionalInterface public interface ToBigDecimalFunction<T> { BigDecimal applyAsBigDecimal(T value); }
第二步
創建工具類 實現接口
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(){ /* 自定義實現對分組後的集合,屬性為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); } }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- Java提效神器Stream的一些冷門技巧匯總
- Java8 如何正確高效的使用並行流
- java BigDecimal類案例詳解
- Java常用函數式接口總結
- java8新特性之stream流中reduce()求和知識總結