Java Programming

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

    ✅ 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);
    
            // Find sum of the first two numbers
            int sumOfTwoNumbers = numbers.stream()
                .limit(2)                      // Take only the first two elements
                .mapToInt(Integer::intValue)  // Convert Integer to int
                .sum();                       // Sum the elements
    
            System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);
        }
    }
    

    ✅ Output:

    Sum of first two numbers = 132
    

    (Since 87 + 45 = 132)


    ✅ Explanation:

    1. numbers.stream(): Converts the list of integers into a Stream of Integer objects.
    2. limit(2): Limits the stream to only the first two elements of the list.
    3. mapToInt(Integer::intValue): Converts each Integer object to primitive int for efficient summation.
    4. sum(): Calculates the sum of the remaining elements in the stream.
    5. Finally, the result is printed using System.out.println().
  • Find Words with Exactly ‘K’ Vowels in a Sentence in Java

    ✅ Correct Problem Sentence:

    Using Java 8 Streams, how do you extract all words from a sentence that contain exactly K vowels?

    ✅ Example:

    import java.util.Arrays;
    
    public class WordsWithVowels {
        public static void main(String[] args) {
            String sentence = "Why only half? Because we compare characters from both ends, no need to go full length.";
            int k = 3;  // Number of vowels to match in each word
    
            Arrays.stream(sentence.split("\\s+"))  // Split sentence into words
                .map(word -> word.replaceAll("[^a-zA-Z]", ""))  // Remove punctuation
                .filter(word -> countVowels(word) == k)         // Filter words with exactly k vowels
                .forEach(System.out::println);                 // Print each matching word
        }
    
        public static long countVowels(String word) {
            return word.chars()
                .mapToObj(ch -> (char) ch)
                .filter(ch -> "aeiouAEIOU".indexOf(ch) != -1)
                .count();
        }
    }
    

    ✅ Explanation:

    1. sentence.split(“\s+”): Splits the sentence by spaces into words.
    2. map(word -> word.replaceAll(“[^a-zA-Z]”, “”)): Removes punctuation (like ?, ., ,) from each word so only letters remain.
    3. filter(word -> countVowels(word) == k): Filters words where the number of vowels equals k (in this example, 3).
    4. forEach(System.out::println): Prints each word that satisfies the condition.
    5. The countVowels(String word) method:
      • Converts the word into a stream of characters (word.chars()).
      • Maps each int character code to a Character object.
      • Filters only vowels (case-insensitive).
      • Returns the count of vowels in the word.

    ✅ Sample Output (with k = 3):

    Because
    compare
    characters
    length

  • Sum of Unique Numbers in a List in Java

    Problem :

    How do you calculate the sum of only unique elements from a list using Java 8 Streams?

    ✅ Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfUniqueNumbers {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(23, 45, 23, 15, 15, 78, 23, 85, 65);
    
            // Calculate sum of unique numbers
            int uniqueNumbersSum = numbers.stream()
                .distinct()                     // Get only unique elements
                .mapToInt(Integer::intValue)    // Convert Integer to int
                .sum();                         // Sum the unique numbers
    
            System.out.println("Sum of unique numbers: " + uniqueNumbersSum);
        }
    }
    

    ✅ Explanation:

    1. numbers.stream(): Creates a stream from the list of integers.
    2. distinct(): Removes duplicate elements from the stream, keeping only unique values.
    3. mapToInt(Integer::intValue): Converts Integer objects to primitive int for efficient processing.
    4. sum(): Computes the sum of the resulting IntStream.
    5. Finally, the result is printed with System.out.println().

    ✅ Output:

    Sum of unique numbers: 311
    

    Because the unique numbers are:

    23 + 45 + 15 + 78 + 85 + 65 = 311

  • Generate Summary Statistics of a List in Java 8

    Problem:

    Using Java 8 Streams, how do you quickly find minimum, maximum, sum, average, and count of numbers in a list without writing separate loops?

    ✅ Example:

    import java.util.Arrays;
    import java.util.IntSummaryStatistics;
    import java.util.List;
    
    public class SummaryStatisticsExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7);
    
            // Generate summary statistics
            IntSummaryStatistics stats = numbers.stream()
                .mapToInt(n -> n)  // Convert Integer to int
                .summaryStatistics();
    
            // Print results
            System.out.println("Minimum: " + stats.getMin());
            System.out.println("Maximum: " + stats.getMax());
            System.out.println("Sum: " + stats.getSum());
            System.out.println("Average: " + stats.getAverage());
            System.out.println("Count: " + stats.getCount());
        }
    }
    

    ✅ Explanation:

    1. numbers.stream(): Create a stream of integers from the list.
    2. mapToInt(n -> n): Converts the Stream<Integer> into an IntStream. This is necessary because IntSummaryStatistics works with primitive int.
    3. summaryStatistics(): This terminal operation generates an IntSummaryStatistics object, which contains:
      • Minimum value → getMin()
      • Maximum value → getMax()
      • Sum of all numbers → getSum()
      • Average → getAverage()
      • Count of elements → getCount()
    4. The results are printed using System.out.println.

    ✅ Output:

    Minimum: 1
    Maximum: 9
    Sum: 25
    Average: 5.0
    Count: 5

  • Find the Sum of the First Two Elements in a List Using Java 8 Streams – Quick & Easy Example

    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.