In this tutorial, we will learn “Find the first non-repeating character in a string using Java 8?”. In order to do that, we are going to leverage the Stream API along with the Collectors.groupingBy collector.

Find the first non-repeated character in a string using Java 8

Find the first non-repeating character in a string using Java 8 Click To Tweet

 

Output:

check if text or string present in a file using java 8

The code above defines a method findFirstNonRepeatedCharacter that takes a string as input and returns an Optional<Character> which represents the first non-repeated character.

Steps:

  1. Convert the input string to a stream of characters using chars().
  2. Convert each character to a Character object.
  3. Use Collectors.groupingBy to group the characters by their counts in a LinkedHashMap.
  4. Filter the entries to find characters with a count of 1.
  5. Map the entry set to characters.
  6. Use findFirst to get the first non-repeated character.

skip method java 8 stream

Find the first non-repeating character in a string using Java 8 Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: