I have this json for student marks and I want to get the Student(s) with highest totalMarks from each standard...I have written this code which is giving the solution but I am not liking the 2 step process. Requesting suggestions to optimize this code to a 1 step solution. Thanks in advance...
json
{
"students": [
{
"fullName": "Student 1",
"standard": 10,
"rollNumber": "1R",
"house": "Red",
"marks": {
"maths": 90,
"english": 90,
"science": 80,
"history": 90
},
"totalMarks": 350,
"sports": [
{
"sportName": "karate",
"status": "purple-belt"
},
{
"sportName": "swimming",
"status": "swimmer"
},
{
"sportName": "karate",
"status": "green-belt"
}
],
"hobbies": [
"programming",
"reading"
]
},
{
"fullName": "Student 2",
"standard": 10,
"rollNumber": "2R",
"house": "Blue",
"marks": {
"maths": 90,
"english": 90,
"science": 90,
"history": 90
},
"totalMarks": 360,
"sports": [
{
"sportName": "cricket",
"status": "all-rounder"
}
],
"hobbies": [
"gaming"
]
}
}
Code
Map<Integer, List<Student>> map8 = reportCard.getStudents().stream().collect(Collectors.groupingBy(Student::getStandard));
map8.keySet().forEach(key -> map8.put(key, map8.get(key).stream().reduce((st1,st2) -> st1.getTotalMarks() > st2.getTotalMarks()? st1:st2).stream().toList()));
map8.forEach((key, value) -> System.out.println(key + "-" + value));
As I said I would like to have this in a single step. Please suggest.