In this tutorial, we will see “How to find the first non-repeated character in a string using Java 8?”find first non repeated character in a string using Java 8
Java 8 – How to find the First Non-Repeated Character in a String? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** * Find the First Non-Repeated Character in a String using Java 8 * @author Deepak Verma * */ import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; public class Find_First_Non_Repeated_Character_in_a_String_using_Java8 { public static void main(String[] args) { System.out.println("First Non-Repeated Character in the String: 'AMAZING' is: "+firstNonRepeatedCharacter("AMAZING")); } public static Optional<Character> firstNonRepeatedCharacter(String inputString) { Map<Character, Long> characterCount = inputString.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return inputString.chars() .mapToObj(c -> (char) c) .filter(c -> characterCount.get(c) == 1) .findFirst(); } } |
Output:
1 | First Non-Repeated Character in the String: 'AMAZING' is: Optional[M] |
find first non repeated character in a string using Java 8
In the above example, The firstNonRepeatedCharacter
method takes a String
input which is supplied through the main method and returns an Optional<Character>
which contains the first non-repeated character in the supplied string, or an empty Optional
if there are no non-repeated characters present there. It uses stream API and collects the frequency of each character in the input string into a Map
of Character
to Long
. The filtered stream of characters is later used to find the first character whose frequency is 1
.
Java 8 – How to find the First Non-Repeated Character in a String? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: