• Find the Sum of the First Two Elements in a List in Java 8

    Problem:
    Using Java 8 Streams, how do you find the sum of the first two numbers in a list?

    ✅ Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfFirstTwoNumbers {
    
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(87, 45, 35, 74, 325);
    
            int sumOfTwoNumbers = numbers.stream()
                    .limit(2)  // Take first two elements
                    .mapToInt(Integer::intValue)  // Convert to int stream
                    .sum();  // Calculate the sum
    
            System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);
        }
    }
    

    ✅ Output:

    Sum of first two numbers = 132

    ✅ Explanation:

    1. The list of numbers: [87, 45, 35, 74, 325]
    2. .stream() creates a stream of elements from the list.
    3. .limit(2) restricts the stream to the first two elements: [87, 45].
    4. .mapToInt(Integer::intValue) converts Integer to primitive int for summing.
    5. .sum() computes the sum of the two numbers:
      87 + 45 = 132.
    6. Finally, print the result: System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);

  • Find the First Repeating Character in a String in Java

    Problem:
    Using Java 8 Streams, how do you find the first repeating character in a given string?

    ✅ Example:

    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class FindFirstRepeatingCharacter {
    
        public static void main(String[] args) {
            String input = "repeating-characters";
    
            input.chars()
                    .mapToObj(ch -> (char) ch)
                    .collect(Collectors.groupingBy(
                            ch -> ch,
                            LinkedHashMap::new,  // Preserve insertion order
                            Collectors.counting()))
                    .entrySet()
                    .stream()
                    .filter(entry -> entry.getValue() > 1)  // Find characters appearing more than once
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .ifPresent(System.out::println);
        }
    }
    

    ✅ Output:

    e

    ✅ Explanation:

    1. Step 1 – Convert String to Character Stream: input.chars().mapToObj(ch -> (char) ch)
      • Converts the string "repeating-characters" to a stream of characters.
    2. Step 2 – Group by Character Count: .collect(Collectors.groupingBy( ch -> ch, LinkedHashMap::new, Collectors.counting()))
      • Creates a LinkedHashMap<Character, Long> where the key is the character and the value is the count of occurrences.
      • LinkedHashMap preserves the order of first appearance.
    3. Step 3 – Filter Repeating Characters: .filter(entry -> entry.getValue() > 1)
      • Keeps only characters that occur more than once.
    4. Step 4 – Pick First Repeating Character: .findFirst()
      • Finds the first character (in the original order) that repeats.
    5. Step 5 – Print the Character: ifPresent(System.out::println);
  • Find the First Non-Repeating Character in a String

    Problem:
    Using Java 8 Streams, how do you find the first non-repeating character in a given string?

    ✅ Example:

    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class FirstNonRepeatingCharacter {
    
        public static void main(String[] args) {
            String input = "Shubham";
    
            input.chars()
                    .mapToObj(ch -> (char) ch)
                    .collect(Collectors.groupingBy(
                            ch -> ch,
                            LinkedHashMap::new,  // Maintain insertion order
                            Collectors.counting()))
                    .entrySet()
                    .stream()
                    .filter(entry -> entry.getValue() == 1)  // Filter non-repeating characters
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .ifPresent(System.out::println);
        }
    }
    

    ✅ Output:

    S

    ✅ Explanation:

    1. Step 1 – Convert String to Stream of Characters: input.chars().mapToObj(ch -> (char) ch)
      • Converts the string "Shubham" into a stream of characters:
        ['S', 'h', 'u', 'b', 'h', 'a', 'm'].
    2. Step 2 – Group by Character Count: .collect(Collectors.groupingBy( ch -> ch, LinkedHashMap::new, Collectors.counting()))
      • Groups characters into a LinkedHashMap<Character, Long>, maintaining insertion order, and counting occurrences.
    3. Step 3 – Filter Non-Repeating Characters: .filter(entry -> entry.getValue() == 1)
      • Keeps only characters that appear exactly once.
    4. Step 4 – Get First Non-Repeating Character: .findFirst()
      • Returns the first non-repeating character (if present).
    5. Step 5 – Print Result: ifPresent(System.out::println);
  • Count the Occurrence of Each Character in a String in Java

    Problem:
    Using Java 8 Streams, how do you count the number of occurrences of each character in a given string (ignoring spaces)?

    ✅ Example:

    import java.util.Arrays;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class CharacterCount {
    
        public static void main(String[] args) {
            String input = "Hello Everyone";
    
            Map<String, Long> charToCount = Arrays.stream(input.replaceAll("\\s+", "").split(""))
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
            charToCount.forEach((character, count) ->
                    System.out.println("Character: " + character + ", Count: " + count));
        }
    }
    

    ✅ Example Output:

    Character: H, Count: 1  
    Character: e, Count: 4  
    Character: l, Count: 2  
    Character: o, Count: 2  
    Character: v, Count: 1  
    Character: r, Count: 1  
    Character: y, Count: 1  
    Character: n, Count: 1  
    

    ✅ Explanation:

    1. Normalization Step: input.replaceAll("\\s+", "")
      • Removes all spaces from the input string "Hello Everyone""HelloEveryone".
    2. Splitting into Characters: .split("")
      • Splits the string into individual characters: ["H", "e", "l", "l", "o", "E", "v", "e", "r", "y", "o", "n", "e"].
    3. Stream Processing: Arrays.stream(...)
      • Converts the array of characters into a stream.
    4. Grouping and Counting: .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
      • Groups characters by themselves and counts the number of occurrences.
    5. Printing the Result: charToCount.forEach((character, count) -> System.out.println(...));
  • Find the 3rd Longest Word in a List in Java

    Problem:
    Using Java 8 Streams, how do you find the third longest word in a list without manually sorting and looping through?

    ✅ Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class ThirdLongestWord {
    
        public static void main(String[] args) {
            List<String> words = Arrays.asList("apple", "banana", "cherry", "mango", "kiwi");
    
            words.stream()
                    .sorted((w1, w2) -> Integer.compare(w2.length(), w1.length()))  // Sort by length descending
                    .skip(2)  // Skip the first two longest words
                    .findFirst()  // Get the 3rd longest word
                    .ifPresent(System.out::println);
        }
    }
    

    ✅ Output:

    apple

    ✅Explanation:

    1. The list of words: ["apple", "banana", "cherry", "mango", "kiwi"]
    2. After sorting by length in descending order: ["banana", "cherry", "apple", "mango", "kiwi"]
    3. .skip(2) skips the first two words:
      • Skips "banana" and "cherry".
    4. .findFirst() picks the next word:
      • Which is "apple".
    5. The output is printed: apple

  • Find the First Odd Number from a List in Java

    Problem:
    Using Java 8 Streams, how do you find the first odd number in a list efficiently, without manually looping?

    ✅ Example:

    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    
    public class FirstOddNumber {
    
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 17, 9, 24, 19);
    
            Optional<Integer> firstOdd = numbers.stream()  // Use stream(), parallelStream() is not necessary here
                    .filter(element -> element % 2 != 0)  // Filter odd numbers
                    .findFirst();  // Find the first matching element
    
            firstOdd.ifPresent(System.out::println);
        }
    }
    

    ✅ Output:

    17

    ✅ ✅ Explanation:

    1. We create a list of numbers: [2, 4, 6, 8, 17, 9, 24, 19]
    2. We use .stream() (sequential stream is sufficient for this purpose): numbers.stream()
    3. .filter(ele -> ele % 2 != 0) filters all odd numbers:
      • Result after filtering: [17, 9, 19].
    4. .findFirst() returns the first element in encounter order, wrapped in Optional<Integer>.
    5. We print the result using: firstOdd.ifPresent(System.out::println);

    ✅ Important Note:

    • Avoid using .parallelStream() here because it may not guarantee order in finding the first element.
      Always prefer .stream() when order matters.

  • 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

    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

  • Check if a String is a Palindrome using Streams?

    Problem:
    How do you check whether a string is a palindrome using Java 8 Streams (without reversing it)?
    A palindrome is a string that reads the same forwards and backwards — like “madam” or “level”

    ✅Example 1: Without Reverse

    import java.util.stream.IntStream;
    
    public class PalindromeCheckStream {
    
        public static void main(String[] args) {
            String input = "madam";
    
            boolean isPalindrome = IntStream.range(0, input.length() / 2)
                    .allMatch(i -> input.charAt(i) == input.charAt(input.length() - 1 - i));
    
            System.out.println("String is Palindrome: " + isPalindrome);
        }
    }
    

    ✅ Output:

    String is Palindrome: true

    ✅ Explanation:

    • We use IntStream.range(0, input.length() / 2) to generate a stream of indices from 0 to input.length() / 2 - 1.
    • For each index i, we check: input.charAt(i) == input.charAt(input.length() - 1 - i) This compares the character from the start of the string with the corresponding character from the end.
    • .allMatch() returns true if all comparisons pass (i.e., the string is a palindrome).
    • We only check up to half the string because beyond that would be redundant.

    ✅ Alternative Approach – Using StringBuilder (without using explicit loops):

    import java.util.stream.IntStream;
    
    public class PalindromeCheckStream {
    
        public static void main(String[] args) {
            String input = "Java knowledge Base";
    
            // Normalize the string: remove spaces and convert to lower case for accurate comparison
            String normalizedInput = input.replaceAll("\\s+", "").toLowerCase();
    
            boolean isPalindrome = normalizedInput.equals(
                    new StringBuilder(normalizedInput).reverse().toString()
            );
    
            System.out.println("Input Parameter: " + input);
            System.out.println("String is Palindrome: " + isPalindrome);
        }
    }
    

    ✅Output:

    Input Parameter: Java knowledge Base
    String is Palindrome: false
    

    ✅ Explanation:

    • First, we normalize the string by:
      • Removing spaces (replaceAll("\\s+", ""))
      • Converting to lowercase (toLowerCase())
        This ensures a fair comparison (ignoring case and spaces).
    • Then, we use StringBuilder’s .reverse() method and check: normalizedInput.equals(new StringBuilder(normalizedInput).reverse().toString());
    • This returns true if the normalized string is the same when reversed, and false otherwise.