如何对Java对象数组多个属性值进行汇总

1、问题

最近在做报表统计相关的任务,中间涉及到很多的地方,需要同时使用SQL进行数据汇总或者在内存进行数据汇总,在内存汇总的时候,遇到一个场景,就是对Java对象数组多个属性值进行汇总。

最后认为方法三使用反射进行处理要通用一点。

2、解决方案

2.1 基于stream流

java 复制代码
    private static BigDecimal calculate(List<Student> studentList, Function<Student,BigDecimal> function){
        return studentList.stream().map(student -> function.apply(student)).reduce(BigDecimal.ZERO,
                BigDecimal::add);
    }

每个字段都需要调用方法:

calculate(studentList,Student::getChinese)

但是这个方法需要调用很多次,而且和对象强相关。

2.2 基于stream流

也可用定义一个数组,一起处理。

java 复制代码
BigDecimal[] reduce = studentList.stream().map(student -> new BigDecimal[]{student.getChinese(), student.getMath(), student.getEnglish()})
				.reduce(new BigDecimal[]{BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO},  (a, b) -> {
					for (int i = 0; i < a.length; i++) {
						b[i] = b[i].add(a[i]);
					}
					return b;
				});

2.3 基于反射

以下方法针对Long、Integer和BigDecimal的字段都进行处理:

java 复制代码
   * 计算列表汇总值
   * @param list 输入
   * @param tClass 输出类
   * @return 汇总结果
   * @param <T>  泛型
   * @throws Exception 异常
   */
  public static <T> T calculateListSum(List<T> list, Class<T> tClass) {
    try {
      T sumObject = tClass.getConstructor().newInstance();
      Field[] declaredFields = tClass.getDeclaredFields();
      Map<Field, BigDecimal> map = new HashMap<>();
      for (Field field : declaredFields) {
        if (field.getType().equals(Long.class) || field.getType().equals(Integer.class) || field.getType().equals(BigDecimal.class)) {
          field.setAccessible(true);
          map.put(field, BigDecimal.ZERO.setScale(2, RoundingMode.HALF_DOWN));
        }
      }


      Set<Map.Entry<Field, BigDecimal>> entries = map.entrySet();
      for (T t : list) {
        for (Map.Entry<Field, BigDecimal> entry : entries) {
          if (entry.getValue() != null && entry.getKey().get(t) != null) {
            try {
              BigDecimal curValue = BigDecimal.ZERO;
              boolean numeric = isNumeric(String.valueOf(entry.getKey().get(t)));
              if (numeric) {
                if (entry.getKey().getType().equals(Long.class)) {
                  curValue = new BigDecimal((Long) entry.getKey().get(t));
                } else if (entry.getKey().getType().equals(Integer.class)) {
                  curValue = new BigDecimal((Integer) entry.getKey().get(t));
                } else if (entry.getKey().getType().equals(BigDecimal.class)) {
                  curValue = (BigDecimal) entry.getKey().get(t);
                }
              }
              entry.setValue(entry.getValue().add(curValue));

            }catch (Exception e) {
              log.info("不支持的字段类型及值,字段={}",entry.getKey().getName());
            }
          }
        }
      }
      Map<String, BigDecimal> resultMap = new HashMap<>();
      map.forEach((key, value) -> resultMap.put(key.getName(), value));
      map.keySet().forEach(field -> ReflectUtil.setFieldValue(sumObject, field, resultMap.get(field.getName())));
      return sumObject;
    }catch (Exception e) {
      log.error("累加计算保存",e);
      return null;
    }
  }
相关推荐
腻害兔1 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:字典、短信、邮件、通知——后台系统的“基础设施四件套“!
java·前端·vue.js·产品经理·ai编程
SeaTunnel1 小时前
从 Python Script 地狱到标准化数据集成框架
大数据·开发语言·python·程序员·代码·seatunnel
碎光拾影2 小时前
ARM交叉工具链各工具作用及IMX6ULL平台LED+蜂鸣器裸机程序实现
java·开发语言·数据库
Marst Code2 小时前
(python)2026Plotly 库评估:交互式可视化到底值不值得引入?
开发语言·python
Miao121313 小时前
微服务 API 测试实践:海外某民宿平台如何构建模式驱动测试基础设施
java·开发语言
腻害兔3 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:支付模块 yudao-module-pay,一个让产品经理都看懂的支付中台设计
java·前端·vue.js·产品经理·ai编程
CRMEB系统商城4 小时前
开源自建还是SaaS订阅?算一笔3年经济账
java·大数据·开发语言·开源
keyipatience5 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
我的xiaodoujiao5 小时前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
weixin_408099675 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能