Hi,
I have some char stored in an ArrayList, I would like to know if there
is a way to
count the occurences of each of these char and return the one that
occurs the most.
Thanks
lots of ways, here's one that's easy to understand -
import java.util.*;
public class Oi
{
public static void main(String[] args)
{
List<Character> l = new ArrayList<Character>();
l.add('c');
l.add('l');
l.add('h');
l.add('l');
if(!l.isEmpty())
{
int maxOccurrences = 0;
char mode = '0';
Map<Character, Integer> m = new HashMap<Character, Integer>();
for(char c : l)
{
m.put(c, m.get(c) == null ? 1 : m.get(c) + 1);
}
for(char c : m.keySet())
{
if(m.get(c) > maxOccurrences)
{
maxOccurrences = m.get(c);
mode = c;
}
System.out.println(c + ":" + m.get(c));
}
System.out.println("Most frequent was " + mode +
" with " + maxOccurrences + " occurrences.");
}
}
}