将List集合中相同属性的数值累加得到一条合计数据

您所在的位置:网站首页 java返回循环 将List集合中相同属性的数值累加得到一条合计数据

将List集合中相同属性的数值累加得到一条合计数据

2023-12-31 03:27| 来源: 网络整理| 查看: 265

在一般统计业务中,大都会有合计数据,即把需要累计的字段加起来。

@Data @AllArgsConstructor @NoArgsConstructor public class MagicList { private BigDecimal aa; private BigDecimal bb; private Integer cc; private String dd; private int ee; }

比如上述类,如果有一个列表,最后一行需要把aa,bb的值累加起来形成合计数据

List magicLists = = new ArrayList(); magicLists.add(new MagicList(new BigDecimal("1"),new BigDecimal("11"),111,"1111",1)); magicLists.add(new MagicList(new BigDecimal("2"),new BigDecimal("22"),222,"2222",2));

一般做法:

//获取所有aa值 1 List aas = magicLists.stream().map(MagicList::getAa).collect(Collectors.toList()); //合计aa值 2 BigDecimal aSum = add(aas); //获取所有bb值 3 List bbs = magicLists.stream().map(MagicList::getBb).collect(Collectors.toList()); //合计bb值 4 BigDecimal bSum = add(bbs); //新建一条合计数据,复制合计的值 5 MagicList magicList = new MagicList(); magicList.setAa(aSum); magicList.setBb(bSum);

可以看到在字段少的情况下,代码还不是很多,但如果有十几个字段呢,代码会非常多且很枯燥,那么有没有简单做法呢?先给出结论,答案当然是有。

第一种方案:

用过mybatis-plus都知道,是可以获取到lambda表达式方法名的(mybatis-plus就是获取到get方法名,然后截取获取字段名称),下方是一个类似mybatis-plus中SFunction接口,关键点就在于序列化,可以看下SerializedLambda 类文档说明。 @FunctionalInterface public interface IFunction extends Function, Serializable { default SerializedLambda getSerializedLambda(){ Method write; try { write = this.getClass().getDeclaredMethod("writeReplace"); write.setAccessible(true); return (SerializedLambda) write.invoke(this); } catch (Exception e) { throw new IllegalArgumentException(); } } default String getImplClass() { return getSerializedLambda().getImplClass(); } default String getImplMethodName() { return getSerializedLambda().getImplMethodName(); } } 利用反射形成合计数据 通过clazz.newInstance()构造合计数据行循环处理每一个IFunction,可以看出1、2出代码就是上方获取aa、bb累计通过get方法获取对应的set方法给第一步构造的数据执行set方法赋值 public static T mapperSum(Class clazz,List list, IFunction... tarClasses){ try{ List type = declaredField.getType(); if (classes.contains(type)) { String fieldName = declaredField.getName(); fieldName = firstLetterToUpper(fieldName); Method method = clazz.getMethod("get"+fieldName); List data = new ArrayList(); for (T t : list) { E e = (E)method.invoke(t); data.add(e); } E add = NumberUtil.add(data); String setMethodName = "set"+fieldName; Method setMethod = clazz.getMethod(setMethodName,type); setMethod.invoke(o,add); } } return o; }catch (Exception e){ throw new IllegalArgumentException(); } } private static String firstLetterToUpper(String str){ char[] array = str.toCharArray(); array[0] -= 32; return String.valueOf(array); } public class NumberUtil { private NumberUtil() { } public static T add(List numbs) { if (numbs == null || numbs.isEmpty()) { return null; } Class


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3