Java Online Compiler
Example: CharacterFrequencyTraditional in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CharacterFrequencyTraditional 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 inputString = "programming"; Map<Character, Integer> charFrequencies = new HashMap<>(); // Step 1: Iterate through each character of the string for (char ch : inputString.toCharArray()) { // Step 2: Use getOrDefault to increment the count // If the character is already in the map, get its current count and add 1. // If not, it means its first occurrence, so set count to 1. charFrequencies.put(ch, charFrequencies.getOrDefault(ch, 0) + 1); } // Step 3: Print the character frequencies System.out.println("Character frequencies (Traditional Method):"); for (Map.Entry<Character, Integer> entry : charFrequencies.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
Output
Clear
ADVERTISEMENTS