This post will discuss how to iterate over a Map in sorted order in Java.

1. Use TreeMap

The HashMap in Java provides good performance but doesn’t maintain any order of its elements. If you want insertion-order iteration with near-HashMap performance, you can use LinkedHashMap. If you want sorted-order iteration, you can use the TreeMap implementation of the Map interface.

A TreeMap is implemented as a Red-black tree and has keys sorted according to their natural ordering, or by a custom comparator. Here’s a working example using Stream API:

Download  Run Code

Output (will vary):

ACGU=4
AMUNXIUAF=9
EO=2
H=1
OCZJWMMAQD=10
RSTFJKPM=8
RXE=3
VICPVI=6
WVNHBUV=7
XTWGP=5

 
Before Java 8, you can do like,

Download  Run Code

Output (will vary):

ACGU=4
AMUNXIUAF=9
EO=2
H=1
OCZJWMMAQD=10
RSTFJKPM=8
RXE=3
VICPVI=6
WVNHBUV=7
XTWGP=5

2. Sorting keys

If you prefer not to use TreeMap and stick to HashMap, you can sort its keys. This can be easily achieved using Java 8:

Download  Run Code

Output (will vary):

BKXVAGACLF=10
CDDJWE=6
CLQVZWO=7
CNRUW=5
EEWT=4
MASGNOIQ=8
N=1
OOJ=3
PBMLONYQZ=9
SI=2

That’s all about iterating over a Map in sorted order in Java.