Java Online Compiler
Example: CharacterFrequencyHashMap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CharacterFrequencyHashMap import java.util.HashMap; import java.util.Map; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { String str = "programming"; Map<Character, Integer> charFrequencies = new HashMap<>(); // Step 1: Iterate through each character of the string for (char c : str.toCharArray()) { // Step 2: Use getOrDefault to safely increment count // If character 'c' is already in the map, get its count and add 1. // If not, get 0 (default value) and add 1, then put it into the map. charFrequencies.put(c, charFrequencies.getOrDefault(c, 0) + 1); } // Step 3: Print the character frequencies System.out.println("Character frequencies (HashMap):"); for (Map.Entry<Character, Integer> entry : charFrequencies.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
Output
Clear
ADVERTISEMENTS