Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / How to sort Map values by key in Java?

How to sort Map values by key in Java?

August 20, 2021 by James Palmer

Short answer
Use a TreeMap. This is precisely what it’s for.
If this map is passed to you and you cannot determine the type, then you can do the following:
SortedSet keys = new TreeSet<>(map.keySet());
for (String key : keys) {
String value = map.get(key);
// do something
}

This will iterate across the map in natural order of the keys.

Longer answer
Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.
For cases where your keys are a complex type that doesn’t implement Comparable or you don’t want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:
// placed inline for the demonstration, but doesn’t have to be a lambda expression
Comparator comparator = (Foo o1, Foo o2) -> {
…
}

SortedSet keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());

Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).
In a HashMap, moving from 1000 items to 10,000 doesn’t really affect your time to lookup an element, but for a TreeMap the lookup time will be about 3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 6 times slower for every element lookup.

Assuming TreeMap is not good for you (and assuming you can’t use generics):
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in