Find the two highest scores

The problem

Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score and the student with the second-highest score.

Breaking it down

Capturing the user input and storing it in a Map where the key is the student's name and the score is the value. Since we need to find the two top scores, we can sort the map by value in descending order and limit the Stream. We can do this by creating a Comparator that will compare the values of the HashMap in reverse order. Finally we can output the values of the stream by using the Stream.forEach and calling the key and value of the map.

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of student: ");
    int studentCount = input.nextInt();
    input.nextLine();

    Map<String, Double> students = new HashMap<String, Double>();

    for (int i = 0; i < studentCount; i++) {
        System.out.print("Enter name for student #" + (i + 1) + ": ");
        String name = input.next();

        System.out.print("Enter score for student #" + (i + 1) + ": ");
        double score = input.nextDouble();

        students.put(name, score);
    }

    input.close();

    Comparator<Entry<String, Double>> byValue = (entry1, entry2) -> entry1
            .getValue().compareTo(entry2.getValue());

    students.entrySet()
            .stream()
            .sorted(byValue.reversed())
            .limit(2)
            .forEach(
                    entry -> {
                        System.out.println("Top student " + entry.getKey()
                                + "'s score is " + entry.getValue());
                    });
}

Output

Enter the number of student: 3
Enter name for student #1: Deb
Enter score for student #1: 60
Enter name for student #2: Jack
Enter score for student #2: 50
Enter name for student #3: Susan
Enter score for student #3: 40
Top student Deb's score is 60.0
Top student Jack's score is 50.0