Sorting Map Based on Its Key
Hi all,
Long time no new post here. Kind of busy this lately and my writing mood was gone. Anyway, today I’m trying to share something related to basic Java programming.
I experienced difficulty to get a Map or HashMap to be sorted. And here I try to share how I handle it.
Sample of Map:
1 2 3 4 5 | Map sampleMap = new HashMap(); sampleMap.put("key1", "value1"); sampleMap.put("key2", "value2"); sampleMap.put("key3", "value3"); sampleMap.put("key4", "value3"); |
If you see, I put the map in ascending order. But later when you try to retrieve the value, you will find the Map is not in order. From what I understand, Map will store the object ANYWHERE inside the memory. Below is my simple sample how to retrieve the value in order.
I store the key inside a List, and sort the list of key:
1 2 | List sortedKeys = new ArrayList(sampleMap.keySet()); Collections.sort(sortedKeys); |
Now you already have a List contains key of the map that has been sorted. The rest, use the sortedKeys to retrieve the object from the sampleMap.
Hope this can be useful.
Many Thanks!!!