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 Share on X

 

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 Share on X

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

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak