我有一个未正确排序的代码段。我需要使用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缩小到标签,因为它显示了不必要的整个字符串。

最佳答案

您应该先订购结果,然后再打印。

对于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();

关于java - 使用TreeMap按键对HashMap进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29126601/

10-16 23:27