我有一个HashMap,其中包含以下值:
Map<String, Integer> map = new HashMap<>();
map.put("name1", 3);
map.put("name2", 14);
map.put("name3", 4);
map.put("name4", 14);
map.put("name5", 2);
map.put("name6", 6);
Run Code Online (Sandbox Code Playgroud)
如何获得所有具有最高价值的钥匙?因此,在此示例中,我得到以下键:
name2
name4
Run Code Online (Sandbox Code Playgroud)
第一步就是要找到最高的值。
int max = Collections.max(map.values());
Run Code Online (Sandbox Code Playgroud)
现在遍历地图的所有条目,并将其添加到与最大值相关联的列表键。
List<String> keys = new ArrayList<>();
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue()==max) {
keys.add(entry.getKey());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您喜欢Java 8 Stream API,请尝试以下操作:
map.entrySet().stream()
.filter(entry -> entry.getValue() == max)
.map(entry -> entry.getKey())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
Nikolas Charalambidis 的响应非常简洁,但假设输入映射更大,一步(迭代)完成可能会更快:
public static List<String> getKeysWithMaxValue(Map<String, Integer> map){
final List<String> resultList = new ArrayList<String>();
int currentMaxValue = Integer.MIN_VALUE;
for (Map.Entry<String, Integer> entry : map.entrySet()){
if (entry.getValue() > currentMaxValue){
resultList.clear();
resultList.add(entry.getKey());
currentMaxValue = entry.getValue();
} else if (entry.getValue() == currentMaxValue){
resultList.add(entry.getKey());
}
}
return resultList;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6525 次 |
| 最近记录: |