How do I sort a Map by Key in Java

The elements in map are stored as {<”testkey1″, “value1″>, <”testkey2″, “value2″>, Map class makes no guarantees as to the order, it is unordered so that we can’t assume anything beyond that, in this how-to, we will look at how to sort a map by Key in Java.

1. Use HashMap sort the collections.

Object[] key = map.keySet().toArray();
for (int i = 0; i < key.length; i++) {

(2) Use TreeMap instead of HashMap, this is precisely what its for, if this map is passed to you and you cannot determine the type, so you can do the following:

TreeSet<String> keys = new TreeSet<String>(map.keySet());
for (String key : keys) {
String value = map.get(key);
// do something

(3) If  TreeMap is not what you want and you can’t use generic:

List sortedKeys=new ArrayList(yourMap.keySet());
// Do what you need with sortedKeys.
Map is an interface defined in JDK, it has three generic implementations: HashMap, TreeMap and LinkedHashMap, also some additional Map implementations are: IdentityHashMap, RenderingHints, TreeMap, WeakHashMap.

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *

  1. Santy

    code looks code but it needs to be udpated to use Generics.