HashMap<Character, Integer> map = new HashMap<Character, Integer>();
You'd normally declare this as the interface. That way if you want to change the implementation, you only have to do so in one place.
Map<Character, Integer> map = new HashMap<>();
Also, you don't need to repeat the types in the map in the latest Java. The <>
tells the compiler to figure it out for you.
char maxappearchar = ' ';
You don't need to declare this at the beginning of the method. You can move it between the two for
loops, since it's only used in the second loop. And you can do without it entirely if you prefer (see below).
for (int i = 0; i < s.length(); i++)
You don't have to manually maintain an index variable. You can just say
for (char c : s.toCharArray())
It's also easier to write c
than s.charAt(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);
}
It's not necessary to do both containsKey
and get
. You can just say
Integer count = map.get(c);
if ( count == null )
{
count = 0;
}
map.put(c, count + 1);
This also simplifies to just one put
line.
int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap
for (Entry<Character, Integer> 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;
As previously mentioned you can write this without maxappearchar
.
int maxValueInMap = Collections.max(map.values());
for (Entry<Character, Integer> entry : map.entrySet())
{
if (entry.getValue() == maxValueInMap)
{
System.out.println("the max char is : " + entry.getKey() + " and displayed " +maxValueInMap+ " times");
return entry.getKey();
}
}
return ' ';
This also does fewer iterations of the loop, as it will exit early. This won't help you in big O terms, but it may cut the actual run time slightly. I'm not sure whether getting the maximum value manually would beat that or not. You'd have to iterate through the entire loop and do a comparison on each iteration, but getting the maximum requires that already.
It also may be important to you to print all the characters with the maximum number of appearances. This only prints the first one encountered. Both versions only return one character.
Consider having the method return a Character
instead of a char
. That would allow you to return null
on an empty string. As it is, you have it returning a space in that case, which is also a possible answer.