packagecom.demo;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;publicclassApp{publicstaticvoidmain(String[]args)throwsIOException{Map<Integer,String>names=newHashMap<>();names.put(2,"Jim");names.put(11,"Tim");names.put(41,"Jane");names.put(5,"Mary");names.put(3,"Zack");//print the map
names.entrySet().stream().forEach(System.out::println);}}
Below output shows key and value printed in random order which is not sorted
1
2
3
4
5
2=Jim3=Zack5=Mary41=Jane11=Tim
Below video also showcases how to sort a map using streams.
2. Sort the map by Key using Streams
Now we will sort the map using key which is id
We can do this by passing Map.Entry.comparingByKey() as an argument to sorted method
packagecom.demo;importjava.io.IOException;importjava.util.Collections;importjava.util.HashMap;importjava.util.Map;publicclassApp{publicstaticvoidmain(String[]args)throwsIOException{Map<Integer,String>names=newHashMap<>();names.put(2,"Jim");names.put(11,"Tim");names.put(41,"Jane");names.put(5,"Mary");names.put(3,"Zack");//print the map
// names.entrySet().stream().forEach(System.out::println);
names.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println);}}
In the below output we can keys are sorted in ascending order as expected
1
2
3
4
5
2=Jim3=Zack5=Mary11=Tim41=Jane
3. Sort by Key in descending order using Streams
To print the sorting order in reverse order we need to pass Comparator.reverseOrder() to Map.Entry.comparingByKey() method as an argument
as shown below
packagecom.demo;importjava.io.IOException;importjava.util.Collections;importjava.util.HashMap;importjava.util.Map;publicclassApp{publicstaticvoidmain(String[]args)throwsIOException{Map<Integer,String>names=newHashMap<>();names.put(2,"Jim");names.put(11,"Tim");names.put(41,"Jane");names.put(5,"Mary");names.put(3,"Zack");//print the map
// names.entrySet().stream().forEach(System.out::println);
names.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);}}
In the below output values are printed in ascending order
1
2
3
4
5
41=Jane2=Jim5=Mary11=Tim3=Zack
5. Sort by Value in descending order using Streams
To print the sorting order in reverse order we need to pass Comparator.reverseOrder() to Map.Entry.comparingByValue() method as an argument
as shown below