USB
USB

Reputation: 6139

How to get key of a specific value in Map

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?

Upvotes: 0

Views: 572

Answers (4)

Payal
Payal

Reputation: 26

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

Upvotes: 0

stevecross
stevecross

Reputation: 5684

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

Upvotes: 1

laune
laune

Reputation: 31300

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

Upvotes: 1

Programmer
Programmer

Reputation: 325

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

Upvotes: 0

Related Questions