Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cn.hutool.core.util.NumberUtil;
- import com.google.common.collect.Lists;
- import lombok.Builder;
- import lombok.Getter;
- import lombok.Setter;
- import java.math.BigDecimal;
- import java.util.Collections;
- import java.util.List;
- import java.util.function.Function;
- public class BatchReduceTest {
- @SafeVarargs
- static <T> List<BigDecimal> batchSum(List<T> list, Function<T, Number>... functions) {
- if (functions == null || functions.length == 0) {
- return Collections.emptyList();
- }
- List<BigDecimal> result = Lists.newArrayListWithCapacity(functions.length);
- for (int i = 0; i < functions.length; i++) {
- // 初始化值,可考虑BigDecimal.Zero
- result.add(null);
- }
- for (T t : list) {
- for (int j = 0; j < functions.length; j++) {
- Function<T, Number> function = functions[j];
- Number apply = function.apply(t);
- Number number = result.get(j);
- if (number == null) {
- result.set(j, new BigDecimal(apply + ""));
- } else {
- result.set(j, NumberUtil.add(apply, number));
- }
- }
- }
- return result;
- }
- @Setter
- @Getter
- @Builder
- static class Foo {
- private Integer integer;
- private BigDecimal bigDecimal;
- }
- public static void main(String[] args) {
- Foo foo1 = Foo.builder().integer(1).bigDecimal(new BigDecimal("10")).build();
- Foo foo2 = Foo.builder().integer(2).bigDecimal(new BigDecimal("12.3")).build();
- Foo foo3 = Foo.builder().integer(8).bigDecimal(new BigDecimal("2")).build();
- List<Foo> fooList = Lists.newArrayList(foo1, foo2, foo3);
- List<BigDecimal> numbers = batchSum(fooList, Foo::getInteger, Foo::getBigDecimal);
- System.out.println(numbers.get(0).intValue() == 11);
- System.out.println(numbers.get(1).compareTo(new BigDecimal("24.3")) == 0);
- System.out.println(numbers);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement