Java 8 Streams – Find the Nth Largest Element in an Array

Problem:
How can you find the 3rd largest element from an integer array using Java 8 Streams?

✅ Correct Code Example:

import java.util.Arrays;
import java.util.Comparator;

public class NthLargestElement {

    public static void main(String[] args) {
        int[] arr = {12, 4, 3, 1, 9, 657};
        int n = 3;  // Find the 3rd largest element

        Arrays.stream(arr)
                .boxed()  // Convert int to Integer for Comparator
                .sorted(Comparator.reverseOrder())  // Sort in descending order
                .skip(n - 1)  // Skip first (n - 1) largest elements
                .findFirst()  // Get the nth largest element
                .ifPresent(System.out::println);
    }
}

✅ ✅ Example Output:

9

✅ ✅ Explanation:

  1. Step 1 – Stream Creation: Arrays.stream(arr) Creates an IntStream from the integer array [12, 4, 3, 1, 9, 657].
  2. Step 2 – Boxing: .boxed() Converts IntStream to Stream<Integer> so we can use Comparator.reverseOrder().
  3. Step 3 – Sorting in Descending Order: .sorted(Comparator.reverseOrder()) After sorting, the stream becomes: [657, 12, 9, 4, 3, 1].
  4. Step 4 – Skip Elements: .skip(n - 1) Skip the first two elements (657 and 12) to get to the 3rd largest.
  5. Step 5 – Get the Nth Largest: .findFirst() Picks the next element in the stream, which is 9.
  6. Step 6 – Print Result: ifPresent(System.out::println);

✅ Using Scanner for System Input:

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class NthLargestElement {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int[] arr = {12, 4, 3, 1, 9, 657};

        System.out.print("Enter the value of n (e.g., 3 for 3rd largest): ");
        int n = scanner.nextInt();

        if (n <= 0 || n > arr.length) {
            System.out.println("Invalid input! n must be between 1 and " + arr.length);
        } else {
            Arrays.stream(arr)
                    .boxed()  // Convert int to Integer for Comparator
                    .sorted(Comparator.reverseOrder())  // Sort in descending order
                    .skip(n - 1)  // Skip first (n - 1) elements
                    .findFirst()  // Pick the nth largest element
                    .ifPresent(System.out::println);
        }

        scanner.close();
    }
}

✅ Sample Run Example:

Input (User types):

3

Output:

9

✅ Explanation:

  1. We use Scanner to take user input for n.
  2. We validate n to ensure it is within the correct range: if (n <= 0 || n > arr.length)
  3. We apply the same stream logic:
    • Sort in descending order.
    • Skip the first (n - 1) elements.
    • Return the nth largest element.
  4. The result is printed using .ifPresent(System.out::println).

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *