如何按字母顺序对 HashMap 条目进行排序?
How to sort HashMap entries in alphabetic order?
我制作了一个程序,可以读取用户的文本,然后显示用户文本的字母频率。我正在试验哈希图,但不确定如何按字母顺序显示我的结果。
我目前有:
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < user.length(); i++) {
Integer count = map.get(user.charAt(i)); // if not in map
if (count == null)
map.put(user.charAt(i), 1);
else
map.put(user.charAt(i), count + 1);
}
作为我存储值的代码,但是当我打印结果时
System.out.println(map.entrySet());
我得到 [a=1, r=2, h=1, y=1]
。 (用于打印 "Harry")
我制作了一个程序,可以读取用户的文本,然后显示用户文本的字母频率。我正在试验哈希图,但不确定如何按字母顺序显示我的结果。
我目前有:
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < user.length(); i++) {
Integer count = map.get(user.charAt(i)); // if not in map
if (count == null)
map.put(user.charAt(i), 1);
else
map.put(user.charAt(i), count + 1);
}
作为我存储值的代码,但是当我打印结果时
System.out.println(map.entrySet());
我得到 [a=1, r=2, h=1, y=1]
。 (用于打印 "Harry")