简体   繁体   中英

Sorting keys alphabetically in LinkedHashMap

I have a LinkedHashMap and I want to sort its keys (which are Strings) alphabetically. However, it won't work with the Collections.sort() method, because it won't take either the LinkedHashMap itself nor the LinkedHashMap's keyset.

My only option is to sort them manually while filling the LinkedHashMap, but before doing that I wanted to know if anyone knows a better way.

The better way is to use a Map which supports an order, like TreeMap.

However, if you have a broken design you can't fix you can do this.

 LinkedHashMap<String, String> map = ...
 TreeMap<String, String> copy = new TreeMap<>(map);
 map.clear();
 map.putAll(copy);

This will happen to work, but if you add a key, your map won't be sorted any more.

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