[英]count number of records based on percentages which are in arraylist
我有一个Arraylist
,其中包含记录列表,并且在每条记录中,我都有一个百分比字段。
我试图显示介于两者之间的学生人数
40%至50%,51%至60%,61%至70%,71%至80%,81%至90%,91%至100%。
例如,假设有5位学生在61%到70%之间,我希望得到的计数为5。我如何动态地获得所有具有指定百分比的学生的计数。 任何人都可以建议我在这方面遵循的方法。
不要算学生,算他们的百分比,像这样:
int count = list.stream()
.map(Student::getPercentage)
.filter(n -> n >= low && n <= high)
.count();
作为集合,ArrayList让我们流传输Student对象,然后将其转换为百分比流,然后对其进行过滤以仅将那些百分比保持在所需范围内,然后对其进行计数。
收集并迭代10个尖括号的范围:
new TreeMap<>(list.stream()
.collect(Collectors.groupingBy(s -> s.getPercentage() / 10, Collectors.counting()))
.forEach((r, n) -> System.out.print(r + "0% to " + ++r + "0% had " + n));
这将整数除以10的结果进行分组(如果不是整数,则将百分比强制转换为int
),添加下游计数操作,然后处理每个整数。
TreeMap包装器按顺序排列百分比范围。
我将进一步采用流方法:
Map<PercentageRange, Integer> counts =
list.stream()
.collect(Collectors.groupingBy(
student -> rangeOf(student.getPercentage())),
Collectors.counting()));
您应该使用lambda表达式。 这将为您提供所有指定范围和学生的地图。
ArrayList<Student> students = new ArrayList<>();
//Each element will have the range as key and all students who fit in the range.
Map<MinMax, List<Student>> map = new HashMap();
//Add all ranges you want to filter your students-list by.
ArrayList<MinMax> minMaxes = new ArrayList<>();
minMaxes.add(new MinMax(20,40);
minMaxes.add(new MinMax(40,60);
minMaxes.add(new MinMax(60,80);
for (MinMax minMax : minMaxes) {
map.put(minMax, students.stream().filter(u -> u.percentage < minMax.min && u.percentage > minMax.max).collect(Collectors.toList()));
}
class MinMax {
private int min;
private int max;
public MinMax(int min, int max) {
this.min = min;
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.