-
Notifications
You must be signed in to change notification settings - Fork 228
/
NthHighestSalaryDemo.java
60 lines (48 loc) · 1.89 KB
/
NthHighestSalaryDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.javatechie;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class NthHighestSalaryDemo {
public static void main(String[] args) {
Map<String, Integer> map1 = new HashMap<>();
map1.put("anil", 1000);
map1.put("bhavna", 1300);
map1.put("micael", 1500);
map1.put("tom", 1600);//output
map1.put("ankit", 1200);
map1.put("daniel", 1700);
map1.put("james", 1400);
Map.Entry<String, Integer> results = getNthHighestSalary(4, map1);
System.out.println(results);
Map<String, Integer> map2 = new HashMap<>();
map2.put("anil", 1000);
map2.put("ankit", 1200);
map2.put("bhavna", 1200);
map2.put("james", 1200);
map2.put("micael", 1000);
map2.put("tom", 1300);
map2.put("daniel", 1300);
//System.out.println(getNthHighestSalary(2, map2));
System.out.println(getDynamicNthHighestSalary(3, map1));
}
public static Map.Entry<String, Integer> getNthHighestSalary(int num, Map<String, Integer> map) {
return map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toList())
.get(num - 1);
}
public static Map.Entry<Integer, List<String>> getDynamicNthHighestSalary(int num, Map<String, Integer> map) {
return map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toList())
))
.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors.toList())
.get(num - 1);
}
}