How can we find the name of the employee having second highest salary in a Map(key -employee name, value-salary) using java 8 stream API?

huangapple go评论88阅读模式
英文:

How can we find the name of the employee having second highest salary in a Map(key -employee name, value-salary) using java 8 stream API?

问题

获取在此哈希映射中存储的员工中薪水第二高的员工的姓名。

英文:

We have a map Map<String, Long> which store employee name as string and employee salary as value. The task is to get the name with of the employee who has the second highest salary among the employees stores in this hashmap.

答案1

得分: 1

以下是翻译好的代码部分:

考虑以下地图作为输入

    Map <StringInteger> 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 <StringInteger> finalResult = map.entrySet()
          .stream()
          .sortedComparator.comparingentry - > -entry.getValue())) //desc order
          .toList()
          .get1; // index start from 0

注意:翻译中的代码部分可能包含HTML转义字符,例如&lt;&gt;,以保持原始格式。

英文:

Consider the following map as input

Map&lt;String,Integer&gt; map = new HashMap&lt;&gt;();
    map.put(&quot;anil&quot;,1000);
    map.put(&quot;ankit&quot;,1200);
    map.put(&quot;bhavna&quot;,1300);
    map.put(&quot;james&quot;,1400);
    map.put(&quot;micael&quot;,1500);
    map.put(&quot;tom&quot;,1600);
    map.put(&quot;daniel&quot;,1700);

We want to fetch second highest salary with employee name. This can be achieved by below code.

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

答案2

得分: 1

你可以通过使用TreeSetEntry::getValue()的比较器来实现这个目标。连续调用两次pollLast来获取第二大的结果。

Map&lt;String, Integer&gt; map = Map.of(
		&quot;Tom&quot;, 15,
		&quot;Jerry&quot;, 17,
		&quot;Silvester&quot;, 10,
		&quot;Tweety&quot;, 12
);

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

Map.Entry&lt;String,Integer&gt; last = set.pollLast();                // Jerry=17
Map.Entry&lt;String,Integer&gt; secondLast = set.pollLast();         // Tom=15
英文:

You can achieve it by collecting into TreeSet with a comparator by the Entry::getValue(). Poll last twice to get the 2nd largest result.

Map&lt;String, Integer&gt; map = Map.of(
		&quot;Tom&quot;, 15,
		&quot;Jerry&quot;, 17,
		&quot;Silvester&quot;, 10,
		&quot;Tweety&quot;, 12
);

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

Map.Entry&lt;String,Integer&gt; last = set.pollLast();                // Jerry=17
		Map.Entry&lt;String,Integer&gt; secondLast = set.pollLast();  // Tom=15

答案3

得分: 1

以下是翻译好的部分:

我很惊讶没有人发布一个简单的`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());
        }
    }
英文:

I'm surprised nobody has posted a simple O(n) solution:

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

答案4

得分: 1

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

英文:

If you use a TreeMap, which is an implementation of Map, you can provide a comparator at the time of its creation to sort the data which is entered into it, automatically. In this way, you can directly fetch your desired result.

huangapple
  • 本文由 发表于 2023年6月22日 03:10:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定