我们如何使用java 8流API在Map中找到具有第二高工资的员工的名字(键-员工姓名,值-工资)?

0qx6xfy6  于 2023-06-28  发布在  Java
关注(0)|答案(4)|浏览(134)

我们有一个map Map<String,Long>,它将员工姓名存储为字符串,将员工工资存储为值。任务是获取在此散列表中存储的员工中薪水第二高的员工的姓名。

pcww981p

pcww981p1#

考虑以下Map作为输入

Map<String,Integer> map = new HashMap<>();
    map.put("anil",1000);
    map.put("ankit",1200);
    map.put("bhavna",1300);
    map.put("james",1400);
    map.put("micael",1500);
    map.put("tom",1600);
    map.put("daniel",1700);

我们希望获得第二高的工资与员工的名字。这可以通过下面的代码实现。

Map.Entry<String,Integer> finalResult = map.entrySet()
      .stream()
      .sorted(Comparator.comparing(entry -> -entry.getValue())) //desc order
      .toList()
      .get(1); // index start from 0
kkbh8khc

kkbh8khc2#

您可以通过Entry::getValue()的比较器将其收集到TreeSet中来实现。轮询最后两次以获得第二大结果。

Map<String, Integer> map = Map.of(
        "Tom", 15,
        "Jerry", 17,
        "Silvester", 10,
        "Tweety", 12
);

NavigableSet<Map.Entry<String,Integer>> set = map.entrySet()
        .stream()
        .collect(Collectors.toCollection(
                () -> new TreeSet<>(Map.Entry.comparingByValue())));

Map.Entry<String,Integer> last = set.pollLast();                // Jerry=17
        Map.Entry<String,Integer> secondLast = set.pollLast();  // Tom=15
6tdlim6h

6tdlim6h3#

我很惊讶没有人发布一个简单的O(n)解决方案:

import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;

public class MyClass {
    public static void main(String args[]) {
        Map<String,Integer> map = new HashMap<>();
        map.put("a",10);
        map.put("b",12);
        map.put("c",20);
        map.put("d",18);
        map.put("e",14);
        map.put("f",16);
    
        Entry<String, Integer> highest = null;
        Entry<String, Integer> secondHighest = null;
        for(Entry<String, Integer> entry:map.entrySet()) {
            if(highest == null) {
                highest = entry;
            } else if(secondHighest == null) {
                secondHighest = entry;
            } else if(highest.getValue() <= entry.getValue()) {
                secondHighest = highest;
                highest = entry;
            } else if(secondHighest.getValue() <= entry.getValue()) {
                secondHighest = entry;
            } else {
                // ignore
            }
        }
        System.err.println("Highest: " + highest.getKey() + ": " + highest.getValue());
        System.err.println("Second highest: " + secondHighest.getKey() + ": " + secondHighest.getValue());
    }
}
vddsk6oq

vddsk6oq4#

如果你使用一个TreeMap,它是Map的一个实现,你可以在它创建的时候提供一个比较器来自动地对输入的数据进行排序。通过这种方式,您可以直接获取所需的结果。

相关问题