My Map contains keys sorted in alphabetical order. When I display it, I'm using entrySet().iterator(), but my results are not in the alphabetical order. How can I get my results in order?
No, your map does not hold elements in alphabetical order. You may have .put(..)
then in that order, but the map does not have a defined iteration order.
Others suggest using SortedSet
, but you can also use LinkedHashMap
. It guarantees iteration order:
This implementation (LinkedHashMap) spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap
Use TreeMap:
A Red-Black tree based
NavigableMap
implementation. The map is sorted according to the natural ordering of its keys, or by aComparator
provided at map creation time, depending on which constructor is used...
For anyone finding this question in 2020 and beyond...
Now that we have streams, you can do something like this:
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEach(System.out::println);
My Map contains keys sorted in alphabetical order
This is not true.
Use http://download.oracle.com/javase/6/docs/api/java/util/SortedMap.html or sort your keys before iterate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With