Java Program to Find the Second Highest Number in ArrayList

Répondu en utilisant GPT-4o-mini par Java Q&A Hub

Question :

Write a program to find the Second Highest number in an ArrayList

Réponse :

Certainly! Below is a simple Java program that demonstrates how to find the second highest number in an ArrayList. The program first checks if the list has at least two distinct elements, then it finds the second highest number.

import java.util.ArrayList;
import java.util.Collections;

public class SecondHighestInArrayList {
    public static void main(String[] args) {
        // Create an ArrayList and add some numbers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(4);
        numbers.add(45);
        numbers.add(99);
        numbers.add(20); // Duplicate value

        // Find the second highest number
        Integer secondHighest = findSecondHighest(numbers);

        if (secondHighest != null) {
            System.out.println("The second highest number is: " + secondHighest);
        } else {
            System.out.println("The ArrayList does not have enough distinct elements.");
        }
    }

    public static Integer findSecondHighest(ArrayList<Integer> numbers) {
        // Remove duplicates by converting to a Set and back to a List
        ArrayList<Integer> uniqueNumbers = new ArrayList<>(new HashSet<>(numbers));

        // Check if there are at least two distinct numbers
        if (uniqueNumbers.size() < 2) {
            return null; // Not enough distinct elements
        }

        // Sort the list in descending order
        Collections.sort(uniqueNumbers, Collections.reverseOrder());

        // Return the second element
        return uniqueNumbers.get(1);
    }
}

Explanation:

  1. ArrayList Creation: We create an ArrayList and populate it with some integers, including a duplicate.
  2. Finding the Second Highest: The findSecondHighest method:
    • Converts the ArrayList to a HashSet to remove duplicates and then back to an ArrayList.
    • Checks if there are at least two distinct numbers.
    • Sorts the list in descending order.
    • Returns the second element from the sorted list.
  3. Output: The program prints the second highest number or a message indicating that there are not enough distinct elements.

Note:

Make sure to import java.util.HashSet if you are using it in the code. You can run this program in any Java environment.