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, int[] prices, int[] sales,String[] items) {
TreeMap<String,Integer>map=new TreeMap<String,Integer>();
int[] profits=new int[items.length];
int maxvalue;
for(int i=0;i<items.length;i++){
profits[i]=sales[i]*prices[i]-costs[i]*sales[i];
if(profits[i]>0){
map.put(items[i],profits[i]);
}
}
Set setOfKeys = map.keySet();
Iterator iterator = setOfKeys.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
Integer value = (Integer)map.get(key);
System.out.println("Key: "+ key+", Value: "+ value);
}
if(!map.isEmpty()){
System.out.println("The maximum value is "+(Collections.max(map.values())));
System.out.println("And it is for");
maxvalue=Collections.max(map.values());
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue()==maxvalue) {
System.out.println(entry.getKey());
break;
}
}
}
else{
System.out.println("There are no profits in this sale");
}
}
The method maxprofitItem gets the below parameters as arguments.
Pass the costs values {100,120,150,1000} Pass the prices values {110,110,200,2000} Pass the sales values {20,100,50,3} Pass the items values {"TV","Graphics card","External Hard disk","Monitor"}
The method calculates the profits and puts the items(Key) and profits(Value) in TreeMap.And the TreeMap looks like below.
Key: Monitor, Value: 3000
Key: External Hard disk, Value: 2500
Key: TV, Value: 200
TreeMap and HashMap puts the key/value pair combination in the same manner. Is there a better way to use TreeMap inorder to find out the key assocaited with the maximum value as it operates in the same manner as HashMap in this regard.
Thanks in advance.
The trick is that you can find maximum value together with its key by providing
Comparator
that compares entries by value.Or using new stream API
You seem to be asking if using
TreeMap
instead ofHashMap
will give you a simpler way to find the key corresponding to the largest value/The answer to that is ... unfortunately ... No.