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:
- Step 1 – Stream Creation:
Arrays.stream(arr)Creates anIntStreamfrom the integer array[12, 4, 3, 1, 9, 657]. - Step 2 – Boxing:
.boxed()ConvertsIntStreamtoStream<Integer>so we can useComparator.reverseOrder(). - Step 3 – Sorting in Descending Order:
.sorted(Comparator.reverseOrder())After sorting, the stream becomes:[657, 12, 9, 4, 3, 1]. - Step 4 – Skip Elements:
.skip(n - 1)Skip the first two elements (657 and 12) to get to the 3rd largest. - Step 5 – Get the Nth Largest:
.findFirst()Picks the next element in the stream, which is9. - 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:
- We use
Scannerto take user input forn. - We validate
nto ensure it is within the correct range:if (n <= 0 || n > arr.length) - We apply the same stream logic:
- Sort in descending order.
- Skip the first
(n - 1)elements. - Return the nth largest element.
- The result is printed using
.ifPresent(System.out::println).