Store counts of characters
HashMap < Character , Integer > counting = new HashMap < > ( ) ; for ( char ch : str . toCharArray ( ) ) { if ( counting . containsKey ( ch ) ) { counting . put ( ch , counting . get ( ch ) + 1 ) ; } else { counting . put ( ch , 1 ) ; } }