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