gpt4 book ai didi

java - 如何在 Java 中按类的属性进行分组

转载 作者:行者123 更新时间:2023-11-30 07:49:32 24 4
gpt4 key购买 nike

所以我有一个学生类,我必须从学生那里获得最好的成绩和分数,但它们都是按他们的类(class) ID 分组的。基本上我必须在每门特定类(class)中获得最好和最差的分数。一切都取自文件 students.txt,这是我目前的代码。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Main
{
public static void main(String[] args) throws IOException {
Path path = Paths.get("src/students.txt");
List<String> lines = Files.readAllLines(path);
ArrayList<Student> students = new ArrayList<>();
for (String line:lines) {
String[] rawlines = line.split(",");
String name = rawlines[0];
String lname = rawlines[1];
String courseID = rawlines[2];
String score = rawlines[3];
double doublescore = Double.parseDouble(score);

Student student = new Student(name, lname, courseID, doublescore);
students.add(student);
}

for (Student s : students) {
System.out.println(s);
}
}
}

我还需要使用线程来实现并行,但这不是我现在主要关心的问题。文件中的行设置如下:Joe, Doe, CS280, 92

最佳答案

您可以使用 Collectors.groupingByCollectors.summarizingDouble得到 DoubleSummaryStatistics其中包括最小值、最大值、平均值等。示例:

拥有:

class Student{
private String name;
private String lname;
private String courseID;
private double score;
// getters 'n setters, constructors, toString, etc
}

List<Student> students = new ArrayList<>(Arrays.asList(
new Student("student1", "student1", "course1", 90),
new Student("student2", "student2", "course2", 86),
new Student("student3", "student3", "course3", 92),
new Student("student4", "student4", "course1", 80),
new Student("student5", "student5", "course2", 93),
new Student("student6", "student6", "course3", 78),
new Student("student7", "student7", "course1", 95),
new Student("student8", "student8", "course2", 83),
new Student("student9", "student9", "course3", 79),
new Student("student10", "student10.", "course1", 88)
));

你可以这样做:

Map<String, DoubleSummaryStatistics> statistics = students.stream()
.collect(Collectors.groupingBy(Student::getCourseID,
Collectors.summarizingDouble(Student::getScore)));

输出:

course3=DoubleSummaryStatistics{count=3, sum=249.000000, min=78.000000, average=83.000000, max=92.000000}, 
course2=DoubleSummaryStatistics{count=3, sum=262.000000, min=83.000000, average=87.333333, max=93.000000},
course1=DoubleSummaryStatistics{count=4, sum=353.000000, min=80.000000, average=88.250000, max=95.000000}

这里有一个学生列表。我们通过 courseId 对学生进行分组,然后根据分数得到每门类(class)的统计数据。然后我们可以获得每个类(class)的值,例如:

statistics.get("course1").getMin();
statistics.get("course2").getMax();

如果有performance concerns关于此过程并且您希望它并行,您可以使用 parallelStream相反:

Map<String, DoubleSummaryStatistics> statistics = students.parallelStream()
.collect(Collectors.groupingBy(Student::getCourseID,

关于java - 如何在 Java 中按类的属性进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com