🎓 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 this blog post, we'll explore how to sort a LinkedHashMap by its keys in Java. A LinkedHashMap in Java is a hash table and linked list implementation of the Map interface, with predictable iteration order.
Sorting becomes necessary when you need to process or display the entries of a LinkedHashMap in a specific, non-insertion order, such as alphabetical or numerical order based on keys.
Sorting LinkedHashMap by Keys in Java
import java.util.*;
import java.util.stream.Collectors;
public class FruitSorter {
// Method to sort LinkedHashMap by keys
public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKey(LinkedHashMap<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
}
public static void main(String[] args) {
// Creating and populating the LinkedHashMap
LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
fruits.put("Apple", 3);
fruits.put("Orange", 2);
fruits.put("Banana", 4);
fruits.put("Grapes", 1);
fruits.put("Pineapple", 5);
// Displaying the original LinkedHashMap
System.out.println("Original LinkedHashMap: " + fruits);
// Sorting the LinkedHashMap by keys
Map<String, Integer> sortedFruits = sortMapByKey(fruits);
// Displaying the sorted LinkedHashMap
System.out.println("Sorted LinkedHashMap by keys: " + sortedFruits);
}
}
Output:
Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by keys: {Apple=3, Banana=4, Grapes=1, Orange=2, Pineapple=5}
Sorting LinkedHashMap by Key in Java Using a Custom Comparator
import java.util.*;
import java.util.stream.Collectors;
public class FruitSorter {
// Custom Comparator
public static Comparator<String> fruitNameComparator() {
return (fruit1, fruit2) -> {
// Custom comparison logic goes here
// For example, sorting based on the length of the fruit name
return Integer.compare(fruit1.length(), fruit2.length());
};
}
// Method to sort LinkedHashMap by keys using a custom comparator
public static <K, V> Map<K, V> sortMapByKeyWithComparator(LinkedHashMap<K, V> map, Comparator<K> comparator) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey(comparator))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
}
public static void main(String[] args) {
// Creating and populating the LinkedHashMap
LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
fruits.put("Apple", 3);
fruits.put("Orange", 2);
fruits.put("Banana", 4);
fruits.put("Grapes", 1);
fruits.put("Pineapple", 5);
// Displaying the original LinkedHashMap
System.out.println("Original LinkedHashMap: " + fruits);
// Sorting the LinkedHashMap by keys using the custom comparator
Map<String, Integer> sortedFruits = sortMapByKeyWithComparator(fruits, fruitNameComparator());
// Displaying the sorted LinkedHashMap
System.out.println("Sorted LinkedHashMap by custom comparator: " + sortedFruits);
}
}
Output:
Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by custom comparator: {Apple=3, Grapes=1, Orange=2, Banana=4, Pineapple=5}
The fruitNameComparator method defines a custom comparator. In this example, it sorts fruit names based on their length. 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