2016-07-31 170 views
2

我已經編寫了下面的代碼,用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相同的方式操作。

在此先感謝。

回答

1

你似乎如果使用TreeMap代替HashMap會給你一個簡單的方法來找到對應於最大價值的關鍵/要問

這個問題的答案是...不幸的是...號

+0

是的,這是我想question.I用樹形圖不同對於上述方案要知道,獲得關鍵的最大值。 – nikthecamel

2

訣竅是,您可以通過提供Comparator來按價值比較條目,從而找到與其關鍵字一起的最大值。

Comparator<Map.Entry<String, Integer>> byValue = Map.Entry.comparingByValue(); 
Map.Entry<String, Integer> maxEntry = Collections.max(map.entrySet(), byValue); 
System.out.println("Maximum value is " + maxEntry.getValue()); 
System.out.println("And it is for " + maxEntry.getKey()); 

或者用新的流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()); 
    }); 
+2

您可以使用'Map.Entry.comparingByValue()'而不是'Comparator.comparing(entry - > entry.getValue())' –

相關問題