1、遍历对比
- public static Character findMostFrequentCharInString(String str) {
- if (StringUtils.isEmpty(str)) {
- return null;
- }
- Map
map = new HashMap<>(); - char[] charArray = str.toCharArray();
- for (char c : charArray) {
- if (map.containsKey(c)) {
- map.put(c, map.get(c) + 1);
- } else {
- map.put(c, 1);
- }
- }
- // 找出最大值
- Integer max = Collections.max(map.values());
- // 遍历map找出key
- for (Map.Entry
entry : map.entrySet()) { - if (entry.getValue() == max) {
- return entry.getKey();
- }
- }
- return null;
- }
2、利用list排序
- public static Character findMostFrequentCharInString1(String str) {
- if (StringUtils.isEmpty(str)) {
- return null;
- }
- Map
map = new HashMap<>(); - char[] charArray = str.toCharArray();
- for (char c : charArray) {
- if (map.containsKey(c)) {
- map.put(c, map.get(c) + 1);
- } else {
- map.put(c, 1);
- }
- }
- // 转换成List
- ArrayList
> list = new ArrayList<>(map.entrySet()); - // 按值倒序排列,第一个元素即为出现最多的字符和次数
- Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
- return list.get(0).getKey();
- }
有没有小伙伴首先想到的是用自带排序的map,如TreeMap,直接使用自带方法
map.firstEntry(); map.firstKey(); map.lastEntry(); map.lastKey(); 获取最大最小值? 遗憾的是TreeMap是按key排序的。