Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

count occurrences of character in string java using hashmap

// Java program to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
    static void characterCount(String inputString)
    {
        // Creating a HashMap containing char
        // as a key and occurrences as  a value
        HashMap<Character, Integer> charCountMap
            = new HashMap<Character, Integer>();
 
        // Converting given string to char array
 
        char[] strArray = inputString.toCharArray();
 
        // checking each char of strArray
        for (char c : strArray) {
            if (charCountMap.containsKey(c)) {
 
                // If char is present in charCountMap,
                // incrementing it's count by 1
                charCountMap.put(c, charCountMap.get(c) + 1);
            }
            else {
 
                // If char is not present in charCountMap,
                // putting this char to charCountMap with 1 as it's value
                charCountMap.put(c, 1);
            }
        }
 
        // Printing the charCountMap
        for (Map.Entry entry : charCountMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "Ajit";
        characterCount(str);
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: difference between two LocalDateTime java 
Java :: java scan a file 
Java :: android xml change button background 
Java :: java.lang.string cannot be cast to java.lang.double react native 
Java :: Using enum values as string literals 
Java :: Cause: zip END header not found 
Java :: convert fileinputstream to string java 
Java :: java swing dialog box 
Java :: java dimension 
Java :: java replace element in list 
Java :: java formatted output 
Java :: read timed out android studio 
Java :: check folder for files java 
Java :: upper en java 
Java :: spring boot MVC config 
Java :: java reverse string 
Java :: java read a line of input 
Java :: android toast 
Java :: java turn string into int 
Java :: java stop script 
Java :: android java back button closeapp 
Java :: char to ascii java 
Java :: declaration of an array in java 
Java :: convert array of char to string java 
Java :: how to call a function in java 
Java :: java search arraylist 
Java :: what is var in java 
Java :: prime number program in java 
Java :: convert arraylist to array int 
Java :: java concatenate strings 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =