Collectors扩展接口 实现BigDecimal的相加
第一步创建 ToBigDecimalFunction接口
import java.math.BigDecimal;
@FunctionalInterface
public interface ToBigDecimalFunction {
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 CH_NOID = Collections.emptySet();
private CollectorsUtil() {
}
@SuppressWarnings("unchecked")
private static Function castingIdentity() {
return i -> (R) i;
}
/**
* Simple implementation class for {@code Collector}.
*
* @param
* the type of elements to be collected
* @param
* the type of the result
*/
static class CollectorImpl implements Collector {
private final Supplier supplier;
private final BiConsumer accumulator;
private final BinaryOperator combiner;
private final Function finisher;
private final Set characteristics;
CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner,
Function finisher, Set characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner,
Set characteristics) {
this(supplier, accumulator, combiner, castingIdentity(), characteristics);
}
@Override
public BiConsumer accumulator() {
return accumulator;
}
@Override
public Supplier supplier() {
return supplier;
}
@Override
public BinaryOperator combiner() {
return combiner;
}
@Override
public Function finisher() {
return finisher;
}
@Override
public Set characteristics() {
return characteristics;
}
}
public static Collector 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);
}
}