Java Data Type How to - Find the most frequent character in a big string








Question

We would like to know how to find the most frequent character in a big string.

Answer

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/* www.  j  av a 2  s.  c  o  m*/
public class Main {

    public static final String LINE = "this is a test this is a test a test test";

    public static Map<Character, Integer> map = new HashMap<>();

    public static void main(String[] args) {

        for (Character c : LINE.toCharArray()) {

            Integer count = map.get(c);
            map.put(c, count != null ? count + 1 : 0);
        }
        System.out.println(Collections.max(map.values()));
    }
}