How to Find the Second Highest Student Average Mark in Java?

Finding the second highest average mark among students can be a common requirement in many applications that deal with student data. In this article, we will explore a solution to find the student with the second highest average mark without creating any new objects. We will be using Java streams and our custom Student class, which holds information about each student such as their average mark, first name, last name, and date of birth. Understanding the Problem To tackle this problem, we need to follow a few key steps. First, we need to sort the list of students based on their averageMark. Since we want to find the second highest average mark, it is essential to sort the list in descending order. According to the problem's requirements, if two students have the same average mark, we should return the younger student. This can be achieved by comparing the dateOfBirth fields of the Student objects. Analyzing the Code Provided From the code you provided, we see a partial implementation of the findSecondBestStudent function. The current implementation is using Comparator.reverseOrder() which is not suitable since we need a custom comparison based on averageMark. Let's build on that and complete the function. Step-by-Step Solution 1. Updating the Comparator The first step is to modify the compare method to ensure that it sorts primarily by averageMark and resolves ties by dateOfBirth: @Override public int compare(Student o1, Student o2) { int markComparison = Double.compare(o2.getAverageMark(), o1.getAverageMark()); // Descending order if (markComparison != 0) { return markComparison; } // If average marks are the same, compare by date of birth (younger first) return o1.dateOfBirth.compareTo(o2.dateOfBirth); } 2. Completing the Function findSecondBestStudent Here is how we can implement the findSecondBestStudent method: public static Student findSecondBestStudent(List students) { return students.stream() .sorted() // Sort based on the custom comparator .distinct() // Ensuring that we have unique average marks .skip(1) // Skip the first (highest) .findFirst() // Get the second (second highest) .orElse(null); // Return null if there is no such student } 3. Complete Implementation Here’s how the entire Student class with our completed method looks: import java.time.LocalDate; import java.util.Comparator; import java.util.List; public class Student implements Comparator { private String firstName; private String lastName; private LocalDate dateOfBirth; private double averageMark; public double getAverageMark() { return averageMark; } @Override public int compare(Student o1, Student o2) { int markComparison = Double.compare(o2.getAverageMark(), o1.getAverageMark()); // Descending order if (markComparison != 0) { return markComparison; } // If average marks are the same, compare by date of birth (younger first) return o1.dateOfBirth.compareTo(o2.dateOfBirth); } public static Student findSecondBestStudent(List students) { return students.stream() .sorted() // Sort using Comparator .distinct() .skip(1) // Skip the first element .findFirst() // Find first in the new stream .orElse(null); // Return null if no student is found } } 4. Notes on the Code The distinct() method is essential to ensure that duplicate average marks are handled properly, allowing us to skip the first occurrence. Using orElse(null) is a safe way to handle scenarios where there might not be a second student with a distinct average mark. Frequently Asked Questions What if there are not enough students? If there are fewer than two students, the method will return null. Handle this case as per your application's requirements. Can I modify the existing students? No, the problem constraints state that you cannot create any new objects. This approach respects that by working only with the given list of students. In conclusion, by utilizing Java's streams and the Comparator interface, we effectively found the student with the second-highest average mark while adhering to the provided constraints. This efficient method takes full advantage of Java's powerful functional programming capabilities, making the code concise and readable.

May 11, 2025 - 11:55
 0
How to Find the Second Highest Student Average Mark in Java?

Finding the second highest average mark among students can be a common requirement in many applications that deal with student data. In this article, we will explore a solution to find the student with the second highest average mark without creating any new objects. We will be using Java streams and our custom Student class, which holds information about each student such as their average mark, first name, last name, and date of birth.

Understanding the Problem

To tackle this problem, we need to follow a few key steps. First, we need to sort the list of students based on their averageMark. Since we want to find the second highest average mark, it is essential to sort the list in descending order. According to the problem's requirements, if two students have the same average mark, we should return the younger student. This can be achieved by comparing the dateOfBirth fields of the Student objects.

Analyzing the Code Provided

From the code you provided, we see a partial implementation of the findSecondBestStudent function. The current implementation is using Comparator.reverseOrder() which is not suitable since we need a custom comparison based on averageMark. Let's build on that and complete the function.

Step-by-Step Solution

1. Updating the Comparator

The first step is to modify the compare method to ensure that it sorts primarily by averageMark and resolves ties by dateOfBirth:

@Override
public int compare(Student o1, Student o2) {
    int markComparison = Double.compare(o2.getAverageMark(), o1.getAverageMark()); // Descending order
    if (markComparison != 0) {
        return markComparison;
    }
    // If average marks are the same, compare by date of birth (younger first)
    return o1.dateOfBirth.compareTo(o2.dateOfBirth);
}

2. Completing the Function findSecondBestStudent

Here is how we can implement the findSecondBestStudent method:

public static Student findSecondBestStudent(List students) {
    return students.stream()
        .sorted() // Sort based on the custom comparator
        .distinct() // Ensuring that we have unique average marks
        .skip(1) // Skip the first (highest)
        .findFirst() // Get the second (second highest)
        .orElse(null); // Return null if there is no such student
}

3. Complete Implementation

Here’s how the entire Student class with our completed method looks:

import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;

public class Student implements Comparator {
    private String firstName;
    private String lastName;
    private LocalDate dateOfBirth;
    private double averageMark;

    public double getAverageMark() {
        return averageMark;
    }

    @Override
    public int compare(Student o1, Student o2) {
        int markComparison = Double.compare(o2.getAverageMark(), o1.getAverageMark()); // Descending order
        if (markComparison != 0) {
            return markComparison;
        }
        // If average marks are the same, compare by date of birth (younger first)
        return o1.dateOfBirth.compareTo(o2.dateOfBirth);
    }

    public static Student findSecondBestStudent(List students) {
        return students.stream()
            .sorted() // Sort using Comparator
            .distinct()
            .skip(1) // Skip the first element
            .findFirst() // Find first in the new stream
            .orElse(null); // Return null if no student is found
    }
}

4. Notes on the Code

  • The distinct() method is essential to ensure that duplicate average marks are handled properly, allowing us to skip the first occurrence.
  • Using orElse(null) is a safe way to handle scenarios where there might not be a second student with a distinct average mark.

Frequently Asked Questions

What if there are not enough students?

If there are fewer than two students, the method will return null. Handle this case as per your application's requirements.

Can I modify the existing students?

No, the problem constraints state that you cannot create any new objects. This approach respects that by working only with the given list of students.

In conclusion, by utilizing Java's streams and the Comparator interface, we effectively found the student with the second-highest average mark while adhering to the provided constraints. This efficient method takes full advantage of Java's powerful functional programming capabilities, making the code concise and readable.