Iterate over a Map in sorted order in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Map; import java.util.Random; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { private static final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String generateRandomWord(int len) { return IntStream.range(0, len) .map(i -> new Random().nextInt(chars.length())) .mapToObj(randomIndex -> String.valueOf(chars.charAt(randomIndex))) .collect(Collectors.joining()); } public static void main(String[] args) { Map<String, Integer> map = IntStream.rangeClosed(1, 10).boxed() .collect(Collectors.toMap(Main::generateRandomWord, i -> i, (oldValue, newValue) -> newValue, TreeMap::new)); map.entrySet().stream().forEach(System.out::println); } } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Map; import java.util.Random; import java.util.TreeMap; public class Main { private static final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String generateRandomWord(int len) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { int randomIndex = new Random().nextInt(chars.length()); sb.append(chars.charAt(randomIndex)); } return sb.toString(); } public static void main(String[] args) { Map<String, Integer> map = new TreeMap<>(); for (int i = 1; i <= 10; i++) { map.put(generateRandomWord(i), i); } for (Map.Entry<String, Integer> stringIntegerEntry : map.entrySet()) { System.out.println(stringIntegerEntry); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { private static final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String generateRandomWord(int len) { return IntStream.range(0, len) .map(i -> new Random().nextInt(chars.length())) .mapToObj(randomIndex -> String.valueOf(chars.charAt(randomIndex))) .collect(Collectors.joining()); } public static void main(String[] args) { Map<String, Integer> map = IntStream.rangeClosed(1, 10).boxed() .collect(Collectors.toMap(Main::generateRandomWord, i -> i, (oldValue, newValue) -> newValue, HashMap::new)); map.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .forEach(System.out::println); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)