Posted by: lrrp | April 17, 2024

Implement the solution for this question using Java 8 functional programming features

Problem – “Find the first non-repeated character in a given string input“. Implement the solution using Java 8 functional programming features

Solution

To improve the code using Java 8 functional programming features, we can leverage streams and lambda expressions to make the code more concise. Here’s the improved version:

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstNonRepeatedCharacter {
    
    public static Character findFirstNonRepeatedCharacter(String inputString) {
        // Precondition check
        if (inputString == null || inputString.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }
        
        // Create a map with characters and their counts
        Map<Character, Long> characterCountMap = inputString.chars()
            .mapToObj(c -> (char) c)
            .collect(LinkedHashMap::new,
                     (map, c) -> map.put(c, map.getOrDefault(c, 0L) + 1),
                     LinkedHashMap::putAll);
        
        // Find the first non-repeated character
        return inputString.chars()
            .mapToObj(c -> (char) c)
            .filter(c -> characterCountMap.get(c) == 1)
            .findFirst()
            .orElseThrow(() -> new RuntimeException("No non-repeated character found in the input string"));
    }

    public static void main(String[] args) {
       System.out.println("  Please  enter  the  input  string  :");
       Scanner in = new Scanner(System.in); // read from System input
       String inputString = in.nextLine();
        Character firstNonRepeated = findFirstNonRepeatedCharacter(inputString);
        System.out.println("First non-repeated character: " + firstNonRepeated);
    }
}

Explanation of changes:

  • Instead of looping through the input string twice to populate the map and find the first non-repeated character, we use Java 8 streams to achieve the same result.
  • In the findFirstNonRepeatedCharacter method:
    • We use inputString.chars() to get an IntStream of characters in the input string.
    • We then convert each integer value to a character using mapToObj(c -> (char) c).
    • We use collect to accumulate the characters into a LinkedHashMap, where each character is a key, and its count is the value.
    • Finally, we use filter to filter out characters with a count of 1 and findFirst to get the first such character, or throw an exception if none is found.
  • The main method remains unchanged.

This approach utilizes Java 8 functional programming features like streams and lambda expressions to achieve the same functionality more concisely and expressively.


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories