[英]get a specific key from HashMap using java stream
我有一个HashMap<Integer, Integer>
,我愿意得到一个特定值的密钥。
例如我的HashMap:
Key|Vlaue
2--->3
1--->0
5--->1
我正在寻找一个java流操作来获取具有最大值的密钥。 在我们的示例中,密钥2具有最大值。
所以2应该是结果。
使用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);
/////////
}
}
您可以对条目进行流式处理,找到最大值并返回相应的键:
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.