1、输入任意一个字符串,统计该字符串各个字符出现的次数,并按出现次数的小到大排序?
public static void main(String[] args) {
String str = "erfdgfdgreerfewgdrgfcvvbgfhgfhgfngfngh";
char[] charStrs = str.toCharArray();
HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
for (int i = 0; i < charStrs.length; i++) {
char mChar = charStrs[i];
if (mHashMap.containsKey(mChar + "")) {
int val = mHashMap.get(mChar + "") + 1;
mHashMap.put(mChar + "", val);
} else {
mHashMap.put(mChar + "", 1);
}
}
// 对map排序
mHashMap = sort(mHashMap);
System.out.println(sort(mHashMap));
}
private static HashMap<String, Integer> sort(HashMap<String, Integer> map) {
Set<Entry<String, Integer>> sets = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
sets);
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
LinkedHashMap<String, Integer> linkMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
linkMap.put(entry.getKey(), entry.getValue());
}
return linkMap;
}