如何在Map中获取特定值的键

时间:2014-06-16 08:48:49

标签: java map hashmap

我正在尝试在Map中找到最大值并获取其相应的密钥。

这是我的maxMin =

  

{3 = 0.1518355013623417,2 = 0.11815917264727849,1 = 0.2467498197744391,   4 = 0.04812703040826949}

for(String keyset: maxMin.keySet()){
 double values = maxMin.get(keyset);
  if (values < min) {
       min = values;
  }
  if (values > max) {
       max = values;
  }
}

我找到了最大值,但是如何找到相应的键?

4 个答案:

答案 0 :(得分:1)

String minkey = null;
String maxkey = null;
for(String keyset: maxMin.keySet()){
  double values = maxMin.get(keyset);
  if (values < min) {
     min = values;
     minkey = keyset;
  }
  if (values > max) {
     max = values;
     maxkey = keyset;
  }
}

答案 1 :(得分:1)

这为您提供了最低和最高值的键:

final Map<String, Integer> map = new HashMap<>();

map.put("lowest", 1);
map.put("5", 5);
map.put("highest", 10);
map.put("3", 3);

Map.Entry<String, Integer> min = null;
Map.Entry<String, Integer> max = null;

for (final Map.Entry<String, Integer> entry : map.entrySet()) {
    if ((null == min) && (null == max)) {
        min = entry;
        max = entry;
        continue;
    }

    if (entry.getValue() < min.getValue()) {
        min = entry;
    }

    if (entry.getValue() > max.getValue()) {
        max = entry;
    }
}

System.out.println("The key for the lowest value is: " + min.getKey());
System.out.println("The key for the highest value is: " + max.getKey());

答案 2 :(得分:0)

How about this:
int pos = 0;
int maxPos = 0;
for(String keyset: maxMin.keySet()){
 pos = pos + 1;
 double values = maxMin.get(keyset);
  if (values < min) {
       min = values;
  }
  if (values > max) {
       max = values;
       maxPos = pos;
  }
}

Set<Integer> keySet = maxMin.keySet();
List<Integer> keyList = new ArrayList<Integer>(keySet);
Integer key = keyList.get(maxPos);

答案 3 :(得分:0)

    for (Entry<String, Double> entry : maxMin.entrySet()) {
        if (entry.getValue() < min) {
            min = entry.getValue();
            minKey = entry.getKey();
        }
        if (entry.getValue() > max) {
            max = entry.getValue();
            maxKey = entry.getKey();
        }
    }