简体   繁体   中英

Get the highest values in a hashmap in java

I have a HashMap which contains the following values:

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:

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:

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. 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. By doing this, we can get the highest value by using 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.

Finally, the last null check is needed in case of an empty map, because there won't be any last entry.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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