简体   繁体   中英

Sorting a HashMap by Keys using TreeMap

I have a code snippet that is not sorting correctly. I need to sort a HashMap by keys using TreeMap, then write out to a text file. I have looked online on sorting and found that TreeMap can sort a HashMap by keys but I am not sure if I am utilizing it incorrectly. Can someone please take a look at the code snippet and advise if this is incorrect?

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();
    }
}

UPDATE:

This is what I get for results when I do a 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)

I am looking to sort this numerically. I have added String s to trim the Key down just to the tags as it was displaying a whole string of stuff that was unnecessary.

You should first order your results, and then print them.

For 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();

For pre 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM