0

I have a collection in the form of key, value pair and I was trying to sort it on the basis of key itself the values in the collection is

cd,20
ef,65
ab,28
gh,76

Now as shown the first is key , please advise me the ways by which I can sort it on the basis of key itself, That is the output that I was looking would be.

ab,28
cd,20
ef,65
gh,76
m.s.
  • 16,063
  • 7
  • 53
  • 88
user1800852
  • 69
  • 1
  • 10

2 Answers2

3

Just create a TreeMap from the original Map. A TreeMap is sorted according to the natural ordering of the keys, and consequently

for (Map.Entry e : treeMap.entrySet()) {
   // generics elided for clarity

will be sorted. From the doc for entrySet():

Returns a Set view of the mappings contained in this map. The set's iterator returns the entries in ascending key order.

Using entrySet() means you can pull the keys and corresponding values in one operation, rather than have to get the keys, and go back to the map for the value. It's a small optimisation, but worth knowing.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1
TreeMap<String, Integer> map = new TreeMap<>();
// insert entries:
map.put("ab", 12);
// ...
// insertion order does not matter
for (String key : map.keySet()) {
    System.out.println(key + ", " + map.get(key));
}
// will always print in sorted order
jlordo
  • 37,490
  • 6
  • 58
  • 83