我已經編寫了下面的代碼,用JAVA中的TreeMap找出具有最大值(Integer)的鍵(String)。獲取與Map中相應最大值關聯的鍵(TreeMap/HashMap)
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");
}
}
maxprofitItem方法獲取以下參數作爲參數。
傳遞成本值 {} 100,120,150,1000傳遞 價格值 {} 110,110,200,2000傳遞 銷售值 {} 20,100,50,3傳遞 的項目值 { 「TV」,」圖形卡「,」外部硬盤「,」顯示器「}
該方法計算利潤並將項目(鍵)和利潤(值)放入TreeMap.And TreeMap如下所示。
重點:監控,價值:3000
重點:外置硬盤,價值:2500
鍵:電視,和值:200
TreeMap和HashMap的放鍵/值對組合同樣的方式。 有沒有更好的方法來使用TreeMap來查找與最大值相關聯的鍵,因爲它在這方面以與HashMap相同的方式操作。
在此先感謝。
是的,這是我想question.I用樹形圖不同對於上述方案要知道,獲得關鍵的最大值。 – nikthecamel