0

I am trying to find max value in a Map and get its corresponding key.

This is my 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;
  }
}

And I found the max but how toget corresponding key?

USB
  • 6,019
  • 15
  • 62
  • 93
  • Relates to and possibly duplicates http://stackoverflow.com/questions/7146990/java-invert-map – Felix Frank Jun 16 '14 at 08:50
  • You could use [Map#entrySet()](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()) – John Jun 16 '14 at 08:53

4 Answers4

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;
  }
}
laune
  • 31,114
  • 3
  • 29
  • 42
1

This gives you the keys of the lowest and highest value:

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());
stevecross
  • 5,588
  • 7
  • 47
  • 85
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);
Programmer
  • 325
  • 5
  • 18
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();
        }
    }
Payal
  • 26
  • 2