麻烦请教下当字符串中有多个字符数量相同时,怎么同时输出?即输出成“出现最多的字符有多个”
public class exam4 {
/**
* Q4.设计一个函数,统计一个字符串中出现频率最高的字符及其出现次数,并利用该函数对用户输入的任意字符串进行统计。
* @author GTzzz
* @param args
*/
public static void main(String[] args) {
String word = "aaaddd";
int num = 0;
char name = 0;
Map hashMap = countWords(word);
for(Map.Entry entry: hashMap.entrySet()){
System.out.println("字符:"+entry.getKey()+",数量:"+entry.getValue());
if ((Integer)entry.getValue() > num ) {
num = (Integer)entry.getValue();
name = (char) entry.getKey();
}
}
String name1 = String.valueOf(name);
System.out.println("出现最多的字符:"+name1+",数量为:"+num);
}
public static Map<Character,Integer> countWords(String word){
Map<Character,Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < word.length(); i++){
char ch = word.charAt(i);
/*System.out.println("ch:"+ch);
System.out.println("map.get:"+map.get(ch));*/
if(map.get(ch) != null){
map.put(ch,map.get(ch)+1);
}else{
map.put(ch,1);
}
}
return map;
}
}
public static void main(String[] args) {
String str = "aaabbbbcccdddddd";
Map<String,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(String.valueOf(str.charAt(i)))){
map.put(String.valueOf(str.charAt(i)),map.get(String.valueOf(str.charAt(i)))+1);
}else{
map.put(String.valueOf(str.charAt(i)),1);
}
}
int max=0;
String maxStr = null;
for(String s:map.keySet()){
int count = map.get(s);
if(count>max){
max=count;
maxStr = s;
}
}
System.out.println("字符"+maxStr+"出现"+max+"次");
}
public static void getString(String str) {
char[] chars = str.toCharArray();
Map charMap = Maps.newHashMap();
for (char aChar : chars) {
charMap.put(String.valueOf(aChar), Optional.ofNullable(charMap.get(String.valueOf(aChar))).orElse(0) + 1);
}
AtomicInteger maxSize = new AtomicInteger(0);
AtomicReference atomicReference = new AtomicReference<>();
charMap.forEach((aChar, size) -> {
if (maxSize.get() < size) {
maxSize.set(size);
atomicReference.set(String.valueOf(aChar));
}
});
System.out.println(atomicReference.get() + "\t" + maxSize.get());
}