Posts

Showing posts with the label First Non Repeating Character in a String

Java Program to Find the First Non Repeating Character in a String

Image
In this section, we will show you three different ways to find first non repeating character in a given String in Java. 1.  Using For loop and Map 2.  Using Java 9 chars() method 3. Using  Java 8 Streams Example 1. Using For loop and Map import java.util.LinkedHashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String str = "america" ; Map < Character , Integer > map = new LinkedHashMap<>(); for ( Character character : str .toCharArray()) { if ( map .containsKey( character )) { map .put( character , map .get( character ) + 1 ); } else { map .put( character , 1 ); } } for ( Map . Entry < Character , Integer > entry : map .entrySet()) { if ( entry .getValue()== 1 ) { System . out .println( entry .getKey()); break ; } }