【发布时间】:2014-01-02 02:46:53
【问题描述】:
我有一个程序,它获取字符串中字符实例的数量,然后将它们放入 HashMap。我有它的工作,但我如何按字母顺序排列 HashMap。这是我的代码:
import java.util.*;
import java.lang.*;
import javax.swing.JOptionPane;
import java.io.*;
public class CharacterCount
{
public static void main(String args[])
{
{
String s = JOptionPane.showInputDialog("Enter in any text.");
String str = s.replaceAll("[., ]", "");
String[] splitted = str.split("");
HashMap hm = new HashMap();
for (int i = 0; i < splitted.length; i++) {
if (!hm.containsKey(splitted[i])) {
hm.put(splitted[i], 1);
} else {
hm.put(splitted[i], (Integer) hm.get(splitted[i]) + 1);
}
}
for (Object word : hm.keySet()) {
if (word.equals("")) {
System.out.println("Spaces: " + (Integer) hm.get(word));
}
else {
System.out.println(word + ": " + (Integer) hm.get(word));
}
}
}
}
}
我需要添加什么来使其按字母顺序排列/重组 HashMap?
【问题讨论】:
-
您不能按字母顺序排列 HashMap。您可以将 HashMap 的条目提取到数组中并对数组进行排序,但 HashMap 的定义是无序的。
-
查看stackoverflow.com/q/2889777/509840。如果你声明它是一个 SortedMap,它会按字母顺序排列。