簡體   English   中英

在java中獲取哈希圖中的最大值

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

我有一個包含以下值的 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);

如何獲得具有最高值的所有鍵? 所以我在這個例子中得到了以下鍵:

name2
name4

第一步是找到最高值。

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

現在遍歷映射的所有條目並將與最大值關聯的鍵添加到列表中。

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

如果您喜歡 Java 8 Stream API,請嘗試以下操作:

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

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;
}

通過僅處理元素一次來實現此目的的另一種方法是使用適當的收集器:

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();

在這里,我們對地圖中的條目進行stream() 通過按條目的值進行分組,我們可以收集到一個新的地圖中。 通過聲明它應該收集到TreeMap中,它將根據它的鍵進行排序。 通過這樣做,我們可以使用lastEntry()獲得最高值。

mapping()用於確保我們將原始映射的鍵作為新映射中的值,否則我們會將條目作為值。

最后,如果地圖為空,則需要最后一次 null 檢查,因為不會有任何最后一個條目。

一個完整的示例,包括導入:

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