Displaying Sorted Java Maps
After sorting a Java Map, you can display the sorted data in various ways, depending on your requirements and the type of Map you are using.
Displaying a Sorted TreeMap
Displaying the contents of a sorted TreeMap
is straightforward, as the keys are already in the desired order.
// Example of displaying a sorted TreeMap
Map<String, Integer> ages = new TreeMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
This will output:
Alice - 25
Bob - 30
Charlie - 35
Displaying a Sorted HashMap
To display a sorted HashMap
, you can first sort the entries using a Comparator
or the Stream API, as shown in the previous section, and then iterate over the sorted entries.
// Example of displaying a sorted HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
// Sort the HashMap by value using a Comparator
Comparator<Map.Entry<String, Integer>> comparator = (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue());
Map<String, Integer> sortedAges = new TreeMap<>(comparator);
sortedAges.putAll(ages);
for (Map.Entry<String, Integer> entry : sortedAges.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
This will output:
Alice - 25
Bob - 30
Charlie - 35
Displaying a Sorted Map using Stream API
You can also use the Java 8 Stream API to sort and display the contents of a Map.
// Example of displaying a sorted Map using Stream API
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
// Sort the Map by value using Stream API and display the results
ages.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));
This will output:
Alice - 25
Bob - 30
Charlie - 35
By using these techniques, you can effectively display the contents of a sorted Java Map in a clear and organized manner, making it easier for users to understand and work with the data.