Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to find min value in Map

Tags:

java

map

min

I am trying to find key with minimum value in Map shown below.

 Map<Node, Integer> freeMap = new TreeMap<>();
 Node minNode = null;
        for (Map.Entry<Node, Integer> entry : freeMap.entrySet()) {
            if (minNode == null) {
                minNode = entry.getKey();
            } else {
                if (entry.getValue() < freeMap.get(minNode)) {
                    minNode = entry.getKey();
                }
            }
        }

Firstly, Is there a straight forward way to find key with minimum value than using foreach loop. Secondly, can you suggest some alternate data structure approach which can be used to store a Node object and an associated Integer value, so I can fetch entry with minimum value in constant time O(1).

like image 622
Meena Chaudhary Avatar asked Oct 22 '14 17:10

Meena Chaudhary


People also ask

How do I find a specific value on a map?

HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How do you compare key values on a map?

We can compare if values contained in the map objects are the same or not by converting all map values to set using values() method and then compare values with the equals() method of the set.

How do I find the value of a map without a key?

Check out the Map. entrySet() and Map. values() methods; those provide access to all values without having to provide a key.


1 Answers

If your goal is to improve time complexity, there's really only one possible change, from O(n log n) to O(n):

 Map<Node, Integer> freeMap = new TreeMap<>();
 Map.Entry<Node, Integer> minEntry = null;
 for (Map.Entry<Node, Integer> entry : freeMap.entrySet()) {
   if (minEntry == null || entry.getValue() < minEntry.getValue()) {
      minEntry = entry;
   }
 }
 Node minNode = minEntry.getKey();
like image 109
Louis Wasserman Avatar answered Sep 29 '22 23:09

Louis Wasserman