How to find the maximum occurring character in a given String? using hashmap java

How to find the maximum occurring character in a given String? using hashmap java

To find the maximum occurring character in a given string using a HashMap in Java, you can use the following steps:

  1. Create a HashMap object to store the character frequencies.
  2. Iterate over the characters in the string and count the frequency of each character.
  3. Find the maximum frequency by iterating over the HashMap and comparing the frequencies of each character.
  4. Return the character with the maximum frequency.

Here's an example of how to implement this in Java:

refe‮:ot r‬lautturi.com
public 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.

Created Time:2017-11-01 20:42:48  Author:lautturi