java 获取字符串中出现最多的字符与次数

80 阅读1分钟

先贴实现代码上来,感觉还有优化空间,后面有时间再进一步优化吧

//1、自定义一个字符串

String temp = "teemttqqwep";

//2、将字符串转为char数组,并遍历这个数组把每个字符对应的次数都记录起来

char[] array = temp.toCharArray();

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

for(char a: array) {

int i = 0;

if(map.containsKey(a)) {

int cut = map.get(a);

map.put(a, ++cut);

}else {

map.put(a, ++i);

}

}

//3、获取出现的最大的次数,遍历keys,取出和出现最大次数相同的记录

List<Map<Character,Integer>> result = new ArrayList<>();

int value = map.values().stream().max(Comparator.comparing(Integer::intValue)).orElse(0);

for (Character character : map.keySet()) {

if (map.get(character) == value){

Map<Character,Integer> tempMap = new HashMap<>();

tempMap.put(character,value);

result.add(tempMap);

System.out.println("出现最多的字符是:" + character + ",次数是:" + value);

}

}

System.out.println(result);

输出:

出现最多的字符是:t,次数是:3
出现最多的字符是:e,次数是:3
[{t=3}, {e=3}]