Advertisement
Guest User

Untitled

a guest
Aug 10th, 2022
510
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. import cn.hutool.core.util.NumberUtil;
  2. import com.google.common.collect.Lists;
  3. import lombok.Builder;
  4. import lombok.Getter;
  5. import lombok.Setter;
  6.  
  7. import java.math.BigDecimal;
  8. import java.util.Collections;
  9. import java.util.List;
  10. import java.util.function.Function;
  11.  
  12. public class BatchReduceTest {
  13.  
  14. @SafeVarargs
  15. static <T> List<BigDecimal> batchSum(List<T> list, Function<T, Number>... functions) {
  16. if (functions == null || functions.length == 0) {
  17. return Collections.emptyList();
  18. }
  19. List<BigDecimal> result = Lists.newArrayListWithCapacity(functions.length);
  20. for (int i = 0; i < functions.length; i++) {
  21. // 初始化值,可考虑BigDecimal.Zero
  22. result.add(null);
  23. }
  24. for (T t : list) {
  25. for (int j = 0; j < functions.length; j++) {
  26. Function<T, Number> function = functions[j];
  27. Number apply = function.apply(t);
  28. Number number = result.get(j);
  29. if (number == null) {
  30. result.set(j, new BigDecimal(apply + ""));
  31. } else {
  32. result.set(j, NumberUtil.add(apply, number));
  33. }
  34. }
  35. }
  36. return result;
  37. }
  38.  
  39. @Setter
  40. @Getter
  41. @Builder
  42. static class Foo {
  43. private Integer integer;
  44. private BigDecimal bigDecimal;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Foo foo1 = Foo.builder().integer(1).bigDecimal(new BigDecimal("10")).build();
  49. Foo foo2 = Foo.builder().integer(2).bigDecimal(new BigDecimal("12.3")).build();
  50. Foo foo3 = Foo.builder().integer(8).bigDecimal(new BigDecimal("2")).build();
  51. List<Foo> fooList = Lists.newArrayList(foo1, foo2, foo3);
  52. List<BigDecimal> numbers = batchSum(fooList, Foo::getInteger, Foo::getBigDecimal);
  53. System.out.println(numbers.get(0).intValue() == 11);
  54. System.out.println(numbers.get(1).compareTo(new BigDecimal("24.3")) == 0);
  55. System.out.println(numbers);
  56. }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement