Java Online Compiler
Example: CharacterFrequencyUsingMap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CharacterFrequencyUsingMap import java.util.HashMap; import java.util.Map; import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize a Scanner to read input from the console Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String inputString = scanner.nextLine(); // Read the entire line of input scanner.close(); // Close the scanner to release resources // Step 2: Create a HashMap to store character frequencies // Keys will be characters, and values will be their counts (integers) Map<Character, Integer> charFrequencyMap = new HashMap<>(); // Step 3: Iterate through each character of the input string for (char ch : inputString.toCharArray()) { // Step 4: For each character, update its count in the map // getOrDefault(key, defaultValue) returns the value for the key, // or defaultValue if the key is not present. // We then increment this count and put it back into the map. charFrequencyMap.put(ch, charFrequencyMap.getOrDefault(ch, 0) + 1); } // Step 5: Print the character frequencies System.out.println("Character frequencies:"); for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) { System.out.println("'" + entry.getKey() + "': " + entry.getValue()); } } }
Output
Clear
ADVERTISEMENTS