To find the maximum occurring character in a given string using a HashMap
in Java, you can use the following steps:
HashMap
object to store the character frequencies.HashMap
and comparing the frequencies of each character.Here's an example of how to implement this in Java:
refe:ot rlautturi.compublic static char findMaxChar(String s) { // Create a HashMap to store the character frequencies HashMap<Character, Integer> freq = new HashMap<>(); // Iterate over the characters in the string and count the frequency of each character for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int count = freq.getOrDefault(c, 0); freq.put(c, count + 1); } // Find the maximum frequency int maxCount = 0; char maxChar = '\0'; for (Map.Entry<Character, Integer> entry : freq.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); maxChar = entry.getKey(); } } // Return the character with the maximum frequency return maxChar; }
In the above example, a method called findMaxChar()
is defined which takes a String
object as an argument and returns a char
value.
The method first creates a HashMap
object called freq
to store the character frequencies. It then iterates over the characters in the string and uses the getOrDefault()
method of the HashMap
to count the frequency of each character.
The getOrDefault()
method returns the value associated with the given key, or a default value if the key is not present in the HashMap
. In this case, the default value is 0.
The method then finds the maximum frequency by iterating over the HashMap
and comparing the frequencies of each character. It uses an enhanced for loop to iterate over the Map.Entry
objects in the HashMap
, and uses the getValue()
and getKey()
methods to get the frequency and character of each entry, respectively.
Finally, the method returns the character with the maximum frequency.