sort a map based on keys and values using java 8

Solutions on MaxInterview for sort a map based on keys and values using java 8 by the best coders in the world

showing results for - "sort a map based on keys and values using java 8"
Johnnie
19 Oct 2019
1Map< Integer, String> map=new HashMap<Integer, String>();
2
3map.put(101, "Hemendra");
4map.put(99, "Andrew");
5map.put(103, "Anish");
6map.put(18, "Mohan");
7map.put(11, "Christine");
8map.put(109, "Rebeca");
9map.put(111, "David");
10map.put(19, "Rahim");
11map.put(10, "Krishna");
12
13Required to sort the map:
14
151. On the basis of keys:
16
17[10=Krishna, 11=Christine, 18=Mohan, 19=Rahim, 99=Andrew, 101=Hemendra, 103=Anish, 109=Rebeca, 111=David]
18
192. On the basis of values:
20
21[99=Andrew, 103=Anish, 11=Christine, 111=David, 101=Hemendra, 10=Krishna, 18=Mohan, 19=Rahim, 109=Rebeca]
22
23Solution:
24
25System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList()));
26System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList()));