Java Programming

  • 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).

  • Filter Strings Starting with a Number in Java 8 Streams

    Problem:

    Given a list of strings, how do you filter only those strings that start with a digit using Java 8 Streams?

    ✅Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class StringStartingWithNumber {
    
        public static void main(String[] args) {
            List<String> list = Arrays.asList("TOrange", "Banana", "2Papaya", "Grapes", "3Pineapple", "Cherry");
    
            list.stream()
                .filter(str -> !str.isEmpty() && Character.isDigit(str.charAt(0)))
                .forEach(System.out::println);
        }
    }
    

    ✅Output:

    2Papaya
    3Pineapple
    

    ✅Explanation:

    1. We define a list of strings: ["TOrange", "Banana", "2Papaya", "Grapes", "3Pineapple", "Cherry"]
    2. We create a stream from the list: list.stream()
    3. The filter() condition: str -> !str.isEmpty() && Character.isDigit(str.charAt(0))
      • Ensures the string is not empty.
      • Checks whether the first character is a digit using Character.isDigit(str.charAt(0)).
    4. The filtered strings are printed using: forEach(System.out::println);
  • Find Numbers Starting with the digit ‘1’

    Problem:
    Given a list of integers (which may contain null values), filter out all the numbers that start with the digit '1' using Java 8 Streams.

    ✅Example:

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class NumbersStartingWithOne {
    
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(123, null, null, 345, 765, 1876, 90, 100);
    
            List<Integer> numbersStartingWithOne = numbers.stream()
                    .filter(num -> num != null && String.valueOf(num).startsWith("1"))
                    .collect(Collectors.toList());
    
            numbersStartingWithOne.forEach(System.out::println);
        }
    }
    

    ✅ Example Output:

    123
    1876
    100

    ✅ Explanation:

    • The list of numbers is: [123, null, null, 345, 765, 1876, 90, 100].
    • We use numbers.stream() to create a stream.
    • The filter() condition: num -> num != null && String.valueOf(num).startsWith("1")
      • Skips null values to avoid NullPointerException.
      • Converts the number to a string and checks if it starts with '1'.
    • .collect(Collectors.toList()) collects the filtered numbers into a new list.
    • Finally, numbersStartingWithOne.forEach(System.out::println); prints: 123 1876 100