Java Program to Find Frequency of each Character in a String - 5 Ways
![Image](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhv2w9ZGDQAHpwi7KM25fhVzgFErgUoj6sKuKPjdHjl7K3OnXgi1uhNFkcziVrniANnAXr1QLkRfQRtl_PYoxot2_wSQ8sNbesLGyEIu9v83_dAtlyZg3ByD3jn9KvfAM-LG05VZVv56IFrJnTDGKIRF8yp6CpkxCP9yuL1p-GKEkhaJcf3mzRP7HbqiHSe/w400-h216/find-frequency-of-each-char.png)
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