zak*_*zak 6 java hashmap java-8 java-stream
我有一个HashMap<Integer, Integer>,我愿意得到一个特定价值的关键.
例如我的HashMap:
Key|Vlaue
2--->3
1--->0
5--->1
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个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);
/////////
}
}
Run Code Online (Sandbox Code Playgroud)
Era*_*ran 10
您可以对条目进行流式处理,找到最大值并返回相应的键:
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
Run Code Online (Sandbox Code Playgroud)