简体   繁体   English

在java中获取哈希图中的最大值

[英]Get the highest values in a hashmap in java

I have a HashMap which contains the following values:我有一个包含以下值的 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);

How do I get all keys with the highest value?如何获得具有最高值的所有键? So that I get the following keys in this example:所以我在这个例子中得到了以下键:

name2
name4

The first step is to find the highest value at all.第一步是找到最高值。

int max = Collections.max(map.values());

Now iterate through all the entries of the map and add to the list keys associated with the highest value.现在遍历映射的所有条目并将与最大值关联的键添加到列表中。

List<String> keys = new ArrayList<>();
for (Entry<String, Integer> entry : map.entrySet()) {
    if (entry.getValue()==max) {
        keys.add(entry.getKey());
    }
}

If you like the Java 8 Stream API, try the following:如果您喜欢 Java 8 Stream API,请尝试以下操作:

map.entrySet().stream()
    .filter(entry -> entry.getValue() == max)
    .map(entry -> entry.getKey())
    .collect(Collectors.toList());

The response from Nikolas Charalambidis is quite neat, but it may be faster to do it in just one step (iteration), supposing that the input map was much larger: 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;
}

Another way to achieve this by only processing the elements once could be to use an appropriate collector:通过仅处理元素一次来实现此目的的另一种方法是使用适当的收集器:

Entry<Integer, Set<String>> highestKey = map.entrySet().stream()
    .collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toSet())))
    .lastEntry();
Set<String> result = highestKey != null ? highestKey.getValue() : Set.of();

Here we stream() over the entries in the map.在这里,我们对地图中的条目进行stream() By grouping by the value of the entries we can collect into a new map.通过按条目的值进行分组,我们可以收集到一个新的地图中。 By stating that it should collect into a TreeMap , it will be sorted according to it's keys.通过声明它应该收集到TreeMap中,它将根据它的键进行排序。 By doing this, we can get the highest value by using lastEntry() .通过这样做,我们可以使用lastEntry()获得最高值。

mapping() is used to make sure we get the keys of the original map as the value in the new map, whithout this we would get the entries as values. mapping()用于确保我们将原始映射的键作为新映射中的值,否则我们会将条目作为值。

Finally, the last null check is needed in case of an empty map, because there won't be any last entry.最后,如果地图为空,则需要最后一次 null 检查,因为不会有任何最后一个条目。

A fully working example including imports:一个完整的示例,包括导入:

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import static java.util.stream.Collectors.*;

class Sorting {

  public static void main(String[] args) {
    Map<String, Integer> map = Map.of(
        "name1", 3,
        "name2", 14,
        "name3", 4,
        "name4", 14,
        "name5", 2,
        "name6", 6);

    Entry<Integer, Set<String>> highestKey = map.entrySet().stream()
        .collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toSet())))
        .lastEntry();
    Set<String> result = highestKey != null ? highestKey.getValue() : Set.of();
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM