
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Map by Key and Value Using Lambda in Java
A Map interface implements the Collection interface that provides the functionality of the map data structure. A Map doesn't contain any duplicate keys and each key is associated with a single value. We can able to access and modify values using the keys associated with them.
In the below two examples, we can able to sort a Map by both key and value with the help of lambda expression.
Example for sorting of Map using Key
import java.util.*; import java.util.stream.*; public class MapSortUsingKeyTest { public static void main(String args[]) { // Sort a Map by their key Map<Integer, String> map = new HashMap<Integer, String>(); map.put(2, "India"); map.put(5, "Australia"); map.put(3, "England"); map.put(1, "Newzealand"); map.put(4, "Scotland"); Map<Integer, String> sortedMap = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray())); } }
Output
Sorted Map: [1=Newzealand, 2=India, 3=England, 4=Scotland, 5=Australia]
Example for sorting of Map using Value
import java.util.*; import java.util.stream.*; public class MapSortUsingValueTest { public static void main(String args[]) { //Sort a Map by their Value Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Jaidev"); map.put(2, "Adithya"); map.put(3, "Vamsi"); map.put(4, "Krishna"); map.put(5, "Chaitanya"); Map<Integer, String> sortedMap = map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray())); } }
Output
Sorted Map: [2=Adithya, 5=Chaitanya, 1=Jaidev, 4=Krishna, 3=Vamsi]
Advertisements