How to find the Entry with largest Key in a Java Map
Last Updated :
19 Jul, 2022
Given a map in Java, the task is to find out the entry in this map with the highest key. Examples:
Input: Map = {ABC = 10, DEF = 30, XYZ = 20}
Output: XYZ = 20
Input: Map = {1 = 40, 2 = 30, 3 = 60}
Output: 3 = 60
Approach
- Iterate the map entry by entry
for (Map.Entry entry : map.entrySet())
{
// Operations
}
- Store the first entry in a reference variable to compare to initially.
- If the current entry’s key is greater than the reference entry’s value, then store the current entry as the reference entry.
- Repeat this process for all the entries in the map.
- In the end, the reference variable has the required entry with the highest key in the map.
- Print this entry
Below is the implementation of the above approach:
Java
import java.util.*;
public class GFG {
public static <K extends Comparable<K>, V> Map.Entry<K, V>
getMaxEntryInMapBasedOnKey(Map<K, V> map)
{
Map.Entry<K, V> entryWithMaxKey = null ;
for (Map.Entry<K, V> currentEntry : map.entrySet()) {
if (
entryWithMaxKey == null
|| currentEntry.getKey()
.compareTo(entryWithMaxKey.getKey())
> 0 ) {
entryWithMaxKey = currentEntry;
}
}
return entryWithMaxKey;
}
public static void print(Map<String, Integer> map)
{
System.out.print( "Map: " );
if (map.isEmpty()) {
System.out.println( "[]" );
}
else {
System.out.println(map);
}
}
public static void main(String[] args)
{
Map<String, Integer> map
= new HashMap<>();
map.put( "ABC" , 10 );
map.put( "DEF" , 30 );
map.put( "XYZ" , 20 );
print(map);
System.out.println(
"Entry with highest key: "
+ getMaxEntryInMapBasedOnKey(map));
}
}
|
Output:
Map: {ABC=10, DEF=30, XYZ=20}
Entry with highest key: XYZ=20
Time complexity: O(NlogN) where N is size of map
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...