java 统计集合中对象的不特定字段的平均值 5C

java 统计集合中对象的不特定字段的平均值如何做?

try {
String methodName = "get"+projectName;
Method method = EsFitnessTestRecordDO.class.getMethod(methodName);
double ave = projectAndSexList.stream().mapToDouble(method).average().average().getAsDouble();//动态统计,报错,怎么写?
double average = projectAndSexList.stream().mapToDouble(EsFitnessTestRecordDO::getBmi).average().getAsDouble();//普通统计bmi字段的平均值,getBmi是EsFitnessTestRecordDO对象中bmi字段的get方法

    }catch (NoSuchMethodException e){

    }
            ![图图片说明](https://img-ask.csdn.net/upload/201810/30/1540893458_171600.png)

1个回答

重复问题,具体回答看:https://ask.csdn.net/questions/705290

 private static Map<List<String>, List<MyClass>> groupListBy(List<MyClass> data, String[] groupByFieldNames) {
    final MethodHandles.Lookup lookup = MethodHandles.lookup();
    List<MethodHandle> handles = 
        Arrays.stream(groupByFieldNames)
              .map(field -> {
                  try {
                      return lookup.findGetter(MyClass.class, field, String.class);
                  } catch (Exception e) {
                      throw new RuntimeException(e);
                  }
              }).collect(toList());
    return data.stream().collect(groupingBy(
            d -> handles.stream()
                        .map(handle -> {
                            try {
                                return (String) handle.invokeExact(d);
                            } catch (Throwable e) {
                                throw new RuntimeException(e);
                            }
                        }).collect(toList())
        ));
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!

相似问题