【Java】对list中多个属性求和

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * BeanUtils
 */
public final class BeanUtils {

   /**
    * 对list的某个int属性求和
    *
    * @param list
    * @param property 属性get方法
    * @param <T>
    * @return
    */
   public static <T> int sumIntProperty(List<T> list, Function<? super T, Integer> property) {
      return list.stream().mapToInt(property::apply).sum();
   }

   /**
    * 对list的某个BigDecimal属性求和
    *
    * @param list
    * @param property 属性get方法
    * @param <T>
    * @return
    */
   public static <T> BigDecimal sumBigDecimalProperty(List<T> list, Function<? super T, BigDecimal> property) {
      return list.stream().mapToLong(value -> property.apply(value).longValue()).mapToObj(BigDecimal::valueOf).reduce(BigDecimal.ZERO, BigDecimal::add);
   }

   /**
    * 对list的多个属性求和
    *
    * @param list
    * @param properties 属性名集
    * @param <T>
    * @return 返回Map
    */
   public static <T> Map<String, Object> sumProperties(List<T> list, String... properties) throws NoSuchMethodException {
      Map<String, Function<T, Object>> propertyMap = getPropertyFunctionMap(list, properties);

      Map<String, Object> result = new HashMap<>();
      for (String property : properties) {
         if (propertyMap.containsKey(property)) {
            Function<T, Object> function = propertyMap.get(property);
            Object sum = list.stream().map(function).reduce(null, (a, b) -> {
               return getSum(property, a, b);
            });
            result.put(property, sum);
         }
      }
      return result;
   }

   /**
    * 对list的多个属性求和
    *
    * @param list
    * @param properties 属性名集
    * @param <T>
    * @return 返回实体对象
    */
   public static <T> T sumObjProperties(List<T> list, String... properties) throws NoSuchMethodException {
      Map<String, Function<T, Object>> propertyMap = getPropertyFunctionMap(list, properties);

      Class clazz = list.get(0).getClass();
      T result = (T) createNewInstance(clazz);

      for (String property : properties) {
         if (propertyMap.containsKey(property)) {
            Function<T, Object> function = propertyMap.get(property);
            Object sum = list.stream().map(function).reduce(null, (a, b) -> {
               return getSum(property, a, b);
            });

            // 设置求和结果给新对象的对应属性
            try {
               Method setterMethod =
                     clazz.getMethod("set" + property.substring(0, 1).toUpperCase() + property.substring(1),
                           sum.getClass());
               setterMethod.invoke(result, sum);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      }
      return result;
   }

   private static Object getSum(String property, Object a, Object b) {
      if (a == null) {
         return b;
      } else if (b == null) {
         return a;
      } else if (a instanceof Integer) {
         return (int) a + (int) b;
      } else if (a instanceof BigDecimal) {
         return ((BigDecimal) a).add((BigDecimal) b);
      } else {
         throw new IllegalArgumentException("不支持的属性计算类型:" + property);
      }
   }

   private static <T> Map<String, Function<T, Object>> getPropertyFunctionMap(List<T> list, String[] properties) throws NoSuchMethodException {
      Map<String, Function<T, Object>> propertyMap = new HashMap<>();
      Class<?> clazz = list.get(0).getClass();
      for (String property : properties) {
         Method method = clazz.getMethod("get" + property.substring(0, 1).toUpperCase() + property.substring(1));
         Class<?> returnType = method.getReturnType();
         if (returnType == Integer.class || returnType == int.class) {
            propertyMap.put(property, (Function<T, Object>) value -> {
               try {
                  return method.invoke(value);
               } catch (Exception e) {
                  e.printStackTrace();
                  return null;
               }
            });
         } else if (returnType == BigDecimal.class) {
            propertyMap.put(property, (Function<T, Object>) value -> {
               try {
                  return method.invoke(value);
               } catch (Exception e) {
                  e.printStackTrace();
                  return null;
               }
            });
         } else {
            throw new IllegalArgumentException("Unsupported type for " + property);
         }
      }
      return propertyMap;
   }

   private static <T> T createNewInstance(Class<T> clazz) {
      try {
         return clazz.getDeclaredConstructor().newInstance();
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java8,可以使用Stream API来对List对象多个值进行求和操作。下面是一个示例代码: ```java import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Integer sum = numbers.stream() .reduce(0, (a, b) -> a + b); System.out.println("List的所有数之和为:" + sum); } } ``` 在上述代码,我们首先定义了一个包含多个整数的List对象numbers。然后,通过调用stream方法将List对象转换为Stream对象,接着使用reduce方法来求和。reduce方法接收两个参数,第一个参数是初始值(这里设置为0),第二个参数是一个BinaryOperator函数,用来将列表的元素进行相加操作。最后,通过打印输出来显示求和的结果。 此外,在Java8,还提供了sum方法来直接求和,可以进一步简化代码。下面是使用sum方法的示例: ```java import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Integer sum = numbers.stream() .mapToInt(Integer::intValue) .sum(); System.out.println("List的所有数之和为:" + sum); } } ``` 在上述代码,我们先通过mapToInt方法将Stream<Integer>映射为Stream<Integer>,然后调用sum方法来求和。最后,通过打印输出来显示求和的结果。 无论是使用reduce方法还是sum方法,都可以对List对象多个值进行求和操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值