- public static void main(String[] args) {
- String string = "abcdekka27qoq";
-
- HashMap<String, Integer> map = count(string);
- System.out.println(map);
-
- TreeMap<String, Integer> treeMap = sortByValue(map);
- System.out.println(treeMap);
- }
- private static HashMap<String, Integer> count(String string) {
- String[] strings = string.split("");
- HashMap<String, Integer> map = new HashMap<String, Integer>();
- for (String s : strings) {
- map.put(s, map.containsKey(s)?map.get(s)+1:1);
- }
- return map;
- }
- private static TreeMap<String, Integer> sortByValue(
- final HashMap<String, Integer> map) {
- TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(
- new Comparator<String>() {
- public int compare(String o1, String o2) {
- Integer i1 = map.get(o1);
- Integer i2 = map.get(o2);
- if (!i1.equals(i2))
- return i2.compareTo(i1);
- return o1.compareTo(o2);
- }
- });
- treeMap.putAll(map);
- return treeMap;
- }
复制代码
回复了你另一个提问,你没理我… |