In this example, we will learn how we can find first non-repeated character using stream so first we will go oversteps how to solve this problem.
Step 1: Iterate all the character from input stream
Step 2: Now we will count character occurrence and will store this result into LinkedHashMap, why we have used LinkedHashmap to store this occurrence because we have to maintain order.
Step 3: Find first non-repeated character – This we can achieve by iterating HashMap and print key of map when occurrence count is 1.
Please find below program for this:-
import java.util.LinkedHashMap; import java.util.Map; public class FirstNonRepeatedCharacter { public static Character firstNonRepeatedCharacter(String input) { Map<Character, Long> charCountMap = input.chars() // This converts the string into a stream of characters. .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()));//his groups the characters and counts their occurrences, storing the result in a LinkedHashMap to maintain the order of insertion. return charCountMap.entrySet() .stream() .filter(entry -> entry.getValue() == 1)//This filters the entries where the character count is 1. .map(Map.Entry::getKey) .findFirst()// This retrieves the first character that matches the condition. .orElse(null); } public static void main(String[] args) { String input = "swiss"; Character result = firstNonRepeatedCharacter(input); if (result != null) { System.out.println("The first non-repeated character is: " + result); } else { System.out.println("There are no non-repeated characters."); } } }