I have written the below code to find out the key(String) that has the maximum value(Integer) using TreeMap in JAVA.
public static void maxprofitItem(int[] costs
The trick is that you can find maximum value together with its key by providing Comparator
that compares entries by value.
Comparator> byValue = Map.Entry.comparingByValue();
Map.Entry maxEntry = Collections.max(map.entrySet(), byValue);
System.out.println("Maximum value is " + maxEntry.getValue());
System.out.println("And it is for " + maxEntry.getKey());
Or using new stream API
map.entrySet().stream()
.max(Map.Entry.comparingByValue())
.ifPresent(maxEntry -> {
System.out.println("Maximum value is " + maxEntry.getValue());
System.out.println("And it is for " + maxEntry.getKey());
});