Middle+
class ExamResult { String studentName; int subjectId; int mark; //1,2,3,4,5 } List<String> getTop5Students(List<ExamResult> list) { }
sobes.tech AI
Answer from AI
To get the top 5 students by average score, you need to group the results by student name, calculate the average score for each, sort in descending order, and take the first five.
Example in Java using Stream API:
import java.util.*;
import java.util.stream.*;
class ExamResult {
String studentName;
int subjectId;
int mark; //1,2,3,4,5
public ExamResult(String studentName, int subjectId, int mark) {
this.studentName = studentName;
this.subjectId = subjectId;
this.mark = mark;
}
}
List<String> getTop5Students(List<ExamResult> list) {
return list.stream()
.collect(Collectors.groupingBy(er -> er.studentName, Collectors.averagingInt(er -> er.mark)))
.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue(Comparator.reverseOrder()))
.limit(5)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
This method returns a list of 5 student names with the highest average score across all subjects.