Posts

Showing posts with the label Java Program to Find Duplicate Characters in a String

Java Program to Find Duplicate Characters in a String - 5 Ways

Image
In this section, we will show you five different ways to find duplicate characters in a given String in Java. 1.  Using For loop  2. Using  Enhanced for loop 3. Using Java 9 chars() method 4. Using Java 8 Streams 5. Using Google Guava MultiSet Example 1. Using For loop import java.util.HashMap ; import java.util.HashSet ; import java.util.Map ; import java.util.Set ; public class Main { public static void main ( String [] args) { String str = "hellojava" ; Map < Character , Integer > occurrences = new HashMap<>(); Set < Character > characterSet = new HashSet<>(); for ( int i = 0 ; i < str .length(); i ++) { char c = str .charAt( i ); if ( occurrences .containsKey( c )) { int count = occurrences .get( c ); occurrences .put( c , ++ count ); characterSet .add( c ); } else { occurrences .put( c , 1 ); }