使用集合获取HashMap中最大值的键

时间:2016-03-11 11:16:10

标签: java collections

我有一个任意对象的HashMap,其值为DoubleHashMap<MyObject, Double> myMap = new HashMap<>();。我可以使用DoubleHashMap中获得最大Collections.max(myMap.values());值,但我需要获取该值的相应键。是否有一种简单的方法可以使用Collections API执行此操作,还是需要迭代器?我已经考虑过获取最大值的位置,然后查询HashMap的位置并得到密钥,但我不知道该怎么做。

编辑:如果需要,我可以将类型从HashMap更改为其他类型,但这两种类型(对象和双重)需要保持不变。

2 个答案:

答案 0 :(得分:3)

只需迭代条目集寻找最大值:

import time
import re
import speedtest_cli
import subprocess



def regex_speedtest(data):
        #output, errors = data.communicate()
        #output1 = str(output)
        Down_Regex = re.compile(r'(Download:).(\d+\.\d+).(Mbit/s)')
        Up_Regex = re.compile(r'(Upload:).(\d+\.\d+).(Mbit/s)')

        for line in data.split("\n"):          # code seems to break at this line.
                print(line)
                #Downmatch = Down_Regex.search(line)
                #Upmatch = Up_Regex.search(line)
        #return (Downmatch.group(2), Upmatch.group(2))



while True:
        now = time.strftime("%H:%M:%S %d %m %Y")
        process = subprocess.Popen(["speedtest-cli", "--server", "2432"], shell=True, stdout=subprocess.PIPE)
        output, errors = process.communicate()
        down, up = regex_speedtest(output)

或者,如果您想获得具有最大值的所有键:

Map.Entry<MyObject, Double> maxEntry = null;
for (Map.Entry<MyObject, Double> entry : map.entrySet()) {
  if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
    maxEntry = entry;
  }
}
MyObject maxKey = maxEntry.getKey();  // Might NPE if map is empty.

答案 1 :(得分:1)

这里有两件事。

1)通过赋予它的价值,无法通过Collections框架获取您的密钥。你需要一个迭代器。

2)告诉它们,键是唯一的而不是值。您必须处理重复值的情况。