学生.java
public class Student{
/*
Metrics examples (out of 100):
mathScore:98
scienceScore:99
englishScore:92
*/
private Map<String, Double> metrics = new HashMap<>();
}
统计
public enum Statistic {
AVERAGE,
MIN,
MAX
}
结果
public class Result {
private Statistic statistic;
private double value;
private String metric;
}
构建可以根据学生列表中请求的指标执行请求的静态分析的引擎的最有效方法是什么
这是一个例子:
假设我有一份学生名单。
List<Student> students = [john, json, elliot, sarah, callie, matt, leigh]; //Assume each entry is an object
我还有我感兴趣的指标列表
List<String> metrics =["mathScore", "scienceScore"]; //Just an example. I can add additional metrics to this list or remove them.
以及我要执行的统计
List<Statistic> stats = [MIN, MAX]; //Just an example. I can request additional operations if necessary.
这里是需要高效构建的方法的签名
public List<Resut> calculate( List<String> requestedMetrics, List<Statistic> requestedStatistics, List<Student> students){
}
这是我最初的想法
- 将 requestedMetrics 和 requestedStatistics 转换为集合 消除重复项。
- 遍历每个指标。对于每个指标, 遍历每个统计数据并计算它。有没有更好的 方式?以及如何分解实现 更小的功能等更清洁的解决方案?
- 创建一个缓存( map )怎么样,这样我们就不需要重新处理了 一切一次又一次?
这是我目前的实现
@Component
public class StatisticalAnalysis {
@Override
public List<Result> calculate(List<Student> students, List<String> metrics, List<Statistic> stats) {
return analyze(new HashSet<>(students), new HashSet<>(metrics), new HashSet<>(stats));
}
public List<Result> analyze(HashSet<Student> students, HashSet<String> metrics, HashSet<Statistic> stats) {
List<Result> calculate = new ArrayList<>(metrics.size());
for (String metric : metrics) {
for (Statistic stat : stats) {
results.add(createResult(students, metric, stat ));
}
}
return results;
}
private Result createResult(HashSet<Student> students, String metric, Statistic stat) {
return new Result(metric, stat, calcStatValue(students, metric, stat));
}
private double calcStatValue(HashSet<Student> students, String metric, Statistic stat) {
List<Double> values = new ArrayList<Double>(students.size());
for(Student measurement: students){
Double value = measurement.getMetric(metric);
if(value!=null)
values.add(value);
}
return performStatOperation(stat, values);
}
private double performStatOperation(Statistic stat, List<Double> values) {
switch (stat) {
case MIN:
return Collections.min(values);
case MAX:
return Collections.max(values);
case AVERAGE:
return values.stream().mapToDouble(val -> val).average().orElse(0.0);
default:
throw new UnsupportedOperationException(String.format("Calculation of Statistic %s is currently unsupported", stat));
}
}
}
最佳答案
与实现您自己的解决方案相反,您可以使用例如 Apache Commons Math 中的统计库。这些提供描述性和汇总统计以及回归和统计测试。这似乎涵盖了您的需要。
Apache Commons Math Statistics 的官方文档链接
关于java - 有效地计算学生列表中给定指标的统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242501/