Posts

Showing posts with the label Occurrences of each Character in a String

Java Program to Find Frequency of each Character in a String - 5 Ways

Image
In this section, we will show you five different ways to find frequency of each Character in a given String in Java. 1.  Using For loop and Map  2. Using  Enhanced for loop and Map 3. Using Java 9 chars() method 4. Using Java 8 Streams 5. Using Google Guava MultiSet Example 1. Using For loop and Map  import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String str = "hello java hello java" ; Map < Character , Integer > occurrences = new HashMap<>(); 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 ); } else { occurrences .put( c , 1 ); } } System . out .println( occurrences ); } } Here we iterate through string chars.  Check whether map