最近在面试,这是遇到的一道习题。不难只是需要思路的转变
思路:
1.输入字符串后排序(其实可以不要)
2.用HashMap键值对处理值的大小
3.定义排序规则(因为hashmap不是list的子类,所以hashmap不支持collections.sort排序,必须转换为list在进行排序操作)
4.然后就可以输出了
public class Demo1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
count(str);
}
public static void count(String str) {
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
char[] chars = str.toCharArray();
Arrays.sort(chars); // 排序
for (int i = 0; i < chars.length; i++) {
char temp = chars[i];
Integer temp1 = hashMap.get(temp);
if (temp1 == null) {
hashMap.put(temp, 1);
} else {
hashMap.put(temp, temp1 + 1);
}
}
/*
* System.out.println("排序前输出结果"); Set<String> keySet = hashMap.keySet();
* keySet.forEach(e -> { System.out.print(e); System.out.print(":");
* System.out.println(hashMap.get(e)); });
*/
// hashmap默认不带排序规则
List<Map.Entry<Character, Integer>> list = new ArrayList<>(hashMap.entrySet()); // 将map的entryset放入集合
// 对list进行排序
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
/* return o1.getValue()-o2.getValue(); */
if (o1.getValue() - o2.getValue() == 0) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o1.getValue() - o2.getValue();
}
}
});
System.out.println("排序后输出结果");
Iterator<Map.Entry<Character, Integer>> iterator = list.iterator();
while (iterator.hasNext()) {
Map.Entry<Character, Integer> itemMap = iterator.next();
Character keyString = itemMap.getKey();
Integer valueInteger = itemMap.getValue();
System.out.println(keyString + ":" + valueInteger);
}
}
}