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

/**
 * 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:

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:

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.

    View all posts