🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In Java 8, you can easily sort a Map by its keys using the Stream API and lambda expressions. This guide will show you how to sort a Map by keys and provide examples to demonstrate the process.
Table of Contents
- Introduction
- Sorting a Map Using TreeMap
- Sorting a Map Using Streams
- Complete Example
- Conclusion
Introduction
A Map in Java is a collection that associates keys with values. Sometimes, you may need to sort a Map by its keys for easier data retrieval and display. Java 8's Stream API makes it straightforward to perform such sorting.
Sorting a Map Using TreeMap
One way to sort a Map by its keys is to use a TreeMap, which sorts entries based on the natural ordering of keys or by a specified comparator.
Example
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortMapUsingTreeMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Banana", 1);
map.put("Apple", 2);
map.put("Cherry", 3);
// Using TreeMap to sort the map by keys
TreeMap<String, Integer> sorted = new TreeMap<>(map);
System.out.println("Sorted Map: " + sorted);
}
}
Output:
Sorted Map: {Apple=2, Banana=1, Cherry=3}
Sorting a Map Using Streams
Another way to sort a Map by its keys is to use the Stream API provided by Java 8. This method is more flexible and can be used to sort the map in various ways.
Example
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortMapUsingStreams {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Banana", 1);
map.put("Apple", 2);
map.put("Cherry", 3);
// Using Stream API to sort the map by keys
Map<String, Integer> sorted = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println("Sorted Map: " + sorted);
}
}
Output:
Sorted Map: {Apple=2, Banana=1, Cherry=3}
Explanation
map.entrySet().stream(): Converts the map's entry set to a stream..sorted(Map.Entry.comparingByKey()): Sorts the entries by key..collect(Collectors.toMap(...)): Collects the sorted entries into a newLinkedHashMapto maintain the insertion order.
Complete Example
Here's a complete example that demonstrates both methods for sorting a Map by keys.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class SortMapByKeysExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Banana", 1);
map.put("Apple", 2);
map.put("Cherry", 3);
// Using TreeMap to sort the map by keys
TreeMap<String, Integer> sortedTreeMap = new TreeMap<>(map);
System.out.println("Sorted Map using TreeMap: " + sortedTreeMap);
// Using Stream API to sort the map by keys
Map<String, Integer> sortedStreamMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println("Sorted Map using Streams: " + sortedStreamMap);
}
}
Output:
Sorted Map using TreeMap: {Apple=2, Banana=1, Cherry=3}
Sorted Map using Streams: {Apple=2, Banana=1, Cherry=3}
Conclusion
Sorting a Map by its keys in Java 8 can be easily achieved using either a TreeMap or the Stream API. The TreeMap approach is straightforward and sorts the map by natural key order or a custom comparator. The Stream API approach offers more flexibility and can be customized further. Both methods ensure the keys are sorted, making data retrieval and display easier.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment