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).
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.
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.
Check out the Map. entrySet() and Map. values() methods; those provide access to all values without having to provide a key.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With