Learnitweb

Java program to find the second largest number in an integer array

import java.util.Arrays;
import java.util.OptionalInt;

public class SecondLargestNumber {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 8, 20, 15, 20, 25}; // Example array

        OptionalInt secondLargest = Arrays.stream(numbers)
                .distinct()                  // Remove duplicates
                .sorted()                    // Sort in ascending order
                .skip(numbers.length - 2)    // Skip to second last element
                .findFirst();                // Get second largest

        secondLargest.ifPresent(num -> System.out.println("Second Largest: " + num));
    }
}

Output:

Second Largest: 20

Using reduce() (Without Sorting)

This approach finds the largest and second largest in one pass, making it more efficient (O(n) time complexity).

import java.util.Arrays;

public class SecondLargestReduce {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 8, 20, 15, 25};

        int max = Arrays.stream(numbers).max().orElse(Integer.MIN_VALUE);
        int secondLargest = Arrays.stream(numbers)
                .filter(n -> n != max) // Exclude the largest number
                .max()
                .orElseThrow(() -> new RuntimeException("No second largest number"));

        System.out.println("Second Largest: " + secondLargest);
    }
}