我已经编写了下面的代码,用JAVA中的TreeMap找出具有最大值(Integer)的键(String)。获取与Map中相应最大值关联的键(TreeMap/HashMap)
public static void maxprofitItem(int[] costs, int[] prices, int[] sales,String[] items) {
TreeMapmap=new TreeMap();
int[] profits=new int[items.length];
int maxvalue;
for(int i=0;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 entry : map.entrySet()) {
if (entry.getValue()==maxvalue) {
System.out.println(entry.getKey());
break;
}
}
}
else{
System.out.println("There are no profits in this sale");
}
}
maxprofitItem方法获取以下参数作为参数。
传递成本值 {} 100,120,150,1000传递 价格值 {} 110,110,200,2000传递 销售值 {} 20,100,50,3传递 的项目值 { “TV”,”图形卡“,”外部硬盘“,”显示器“}
该方法计算利润并将项目(键)和利润(值)放入TreeMap.And TreeMap如下所示。
重点:监控,价值:3000
重点:外置硬盘,价值:2500
键:电视,和值:200
TreeMap和HashMap的放键/值对组合同样的方式。 有没有更好的方法来使用TreeMap来查找与最大值相关联的键,因为它在这方面以与HashMap相同的方式操作。
在此先感谢。