[英]get a specific key from HashMap using java stream
I have a HashMap<Integer, Integer>
and i'm willing to get the key of a specific value. 我有一个HashMap<Integer, Integer>
,我愿意得到一个特定值的密钥。
for example my HashMap: 例如我的HashMap:
Key|Vlaue
2--->3
1--->0
5--->1
I'm looking for a java stream operation to get the key that has the maximum value. 我正在寻找一个java流操作来获取具有最大值的密钥。 In our example the key 2 has the maximum value. 在我们的示例中,密钥2具有最大值。
So 2 should be the result. 所以2应该是结果。
with a for loop it can be possible but i'm looking for a java stream way. 使用for循环它是可能的,但我正在寻找一种java流方式。
import java.util.*;
public class Example {
public static void main( String[] args ) {
HashMap <Integer,Integer> map = new HashMap<>();
map.put(2,3);
map.put(1,0);
map.put(5,1);
/////////
}
}
You can stream over the entries, find the max value and return the corresponding key: 您可以对条目进行流式处理,找到最大值并返回相应的键:
Integer maxKey =
map.entrySet()
.stream() // create a Stream of the entries of the Map
.max(Comparator.comparingInt(Map.Entry::getValue)) // find Entry with
// max value
.map(Map.Entry::getKey) // get corresponding key of that Entry
.orElse (null); // return a default value in case the Map is empty
public class GetSpecificKey{
public static void main(String[] args) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(2,3);
map.put(1,0);
map.put(5,1);
System.out.println(
map.entrySet().stream().
max(Comparator.comparingInt(Map.Entry::getValue)).
map(Map.Entry::getKey).orElse(null));
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.