Write a program to find the Second Highest number in an ArrayList
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);
}
}
ArrayList
and populate it with some integers, including a duplicate.findSecondHighest
method:
ArrayList
to a HashSet
to remove duplicates and then back to an ArrayList
.Make sure to import java.util.HashSet
if you are using it in the code. You can run this program in any Java environment.