Finding the most common character in a string with a hash map I created a method for finding the most common character in a string (using HashMap):

public static char getMaxViaHashmap ( String s) {     
         HashMap&lt;Character, Integer&gt; map = new HashMap&lt;Character, Integer&gt;(); 
         char maxappearchar = ' ';
         for (int i = 0; i &lt; s.length(); i++)
         {
              if ( map.containsKey(s.charAt(i)))
              {
                    map.put (s.charAt(i), map.get(s.charAt(i)) + 1 );
              }       
              else
              {
                map.put (s.charAt(i), 1);
              }           
         }  


          int maxValueInMap=(Collections.max(map.values()));  // This will return max value in the Hashmap    
            for (Entry&lt;Character, Integer&gt; entry : map.entrySet())
            {  
                if (entry.getValue()==maxValueInMap)
                {
                    System.out.println("the max char is : " + entry.getKey() + "  and displayed  " +maxValueInMap+ "  times");     // Print the key with max value
                    maxappearchar = entry.getKey();
                }

            }
            return maxappearchar;
    }


Questions:


What is the performance cost (in terms of \$O()\$)?
What is the memory cost (in terms of \$O()\$)?
Normally operations on a hashmap should be pretty much constant (O(n)=1), so it's something like O(n) = n + 2*m (number of characters in the String plus twice the amount of different characters in the string, since you iterate twice over the map to find the max and the corresponding character).
Memory should also be pretty much linear, since you are storing one int per different character.


As Collections.max iterates once over the map, iterating again over it to get the corresponding character is pretty much wasted. You could remove the Collections.max call and start by iterating over the entries and remember the one with the highest count, thus saving the whole Collections.max iteration ( getting a O(n) = n + m runtime).

Your hashmap will probably need to resize itself once or twice (at least). You can reduce the need for that by choosing a good start size for your hashmap (aprox. the number of different characters in your string, which depends on the language), but normally that shouldn't be that much gain (depending on the length of the sentence and the amount of different characters in the sentence).