使用TreeMap按键排序HashMap

时间:2015-03-18 15:51:00

标签: java sorting

我有一个没有正确排序的代码段。我需要使用TreeMap按键对HashMap进行排序,然后写出文本文件。我已经在线查看了排序,发现TreeMap可以通过键对HashMap进行排序,但我不确定我是否正在使用它。有人可以看一下代码片段,并告知这是不正确的吗?

public void compareDICOMSets() throws IOException
    {
        FileWriter fs;
        BufferedWriter bw;
        fs = new FileWriter("dicomTagResults.txt");
        bw = new BufferedWriter(fs);
        Map<String, String> sortedMap = new TreeMap<String, String>();
        for (Entry<String, String> entry : dicomFile.entrySet())
        {       
            String s = entry.toString().substring(0, Math.min(entry.toString().length(), 11));
            if(dicomTagList.containsKey(entry.getKey()))
            {
                sortedMap.put(s, entry.getValue());
                Result.put(s, entry.getValue());
                bw.write(s + entry.getValue() + "\r\n");                
            }
        }
        bw.close();
        menu.showMenu();
    }
}

更新:

这是我在进行println时得​​到的结果:

(0008,0080)
(0008,0092)
(0008,1010)
(0010,4000)
(0010,0010)
(0010,1030)
(0008,103E)
(0008,2111)
(0008,1050)
(0012,0040)
(0008,0094)
(0010,1001)

我希望用数字排序。我已经添加了String来将Key修剪到标签,因为它显示了一整串不必要的东西。

1 个答案:

答案 0 :(得分:2)

您应首先订购结果,然后打印出来。

对于Java 8:

Map<String, String> Result = ...;

// This orders your Result map by key, using String natural order
Map<String, String> ordered = new TreeMap<>(Result);

// Now write the results
BufferedWriter bw = new BufferedWriter(new FileWriter("dicomTagResults.txt"));
ordered.forEach((k, v) -> bw.write(k + v + "\r\n");

bw.close();

对于Java 8之前:

Map<String, String> Result = ...;

// This orders your Result map by key, using String natural order
Map<String, String> ordered = new TreeMap<>(Result);

// Now write the results
BufferedWriter bw = new BufferedWriter(new FileWriter("dicomTagResults.txt"));
for (Map.Entry<String, String> entry : ordered.entrySet()) {
    String k = entry.getKey();
    String v = entry.getValue();
    bw.write(k + v + "\r\n");
}

bw.close();