2016-04-09 168 views
0

我有一段代碼,我試圖按照降序排列TreeMap中的密鑰,因爲當我只使用TreeMap時,它會根據按升序排列的鍵進行排序。我得到的錯誤是:如何自定義TreeMap以按降序對鍵進行排序?

沒有適用於TreeMap的構造函數。

這裏有什麼問題?

import java.util.TreeMap; 
import java.util.Map; 
import java.util.Comparator; 
import java.util.Map.Entry; 
import java.util.SortedMap; 

public class ChangeMachine { 


    public TreeMap<Double, Integer> dispenseChange(Double changeAmount, TreeMap<Double, Integer> coinsMap) { 
     TreeMap<Double, Integer> coinDispenserMap = new TreeMap<>(); 
     for (Map.Entry<Double, Integer> coin : coinsMap.entrySet()) { 
      if (!(changeAmount > coin.getKey())) { 
       coinDispenserMap.put(coin.getKey(), 0); 
       continue; 
      } 
      int noOfCoins = (int) (changeAmount/coin.getKey()); 
      coinDispenserMap.put(coin.getKey(), noOfCoins); 
      Double remainder = changeAmount % coin.getKey(); 
      changeAmount = remainder; 
      if (changeAmount == 0.0) { 
       break; 
      } 
     } 
     return coinDispenserMap; 

    } 


    public static void main(String[] args) { 
     ChangeMachine ref = new ChangeMachine(); 
     TreeMap<Double, Integer> coinsMap = new TreeMap<Double, Integer>(new Comparator<Entry<Double, Integer>>() { 
      public int compare(Entry<Double, Integer> coin1, Entry<Double, Integer> coin2) { 
       return (coin2.getKey().compareTo(coin1.getKey())); 
      } 
     }); 
     coinsMap.put(0.25, 10); 
     coinsMap.put(0.01, 10); 
     coinsMap.put(0.05, 10); 
     coinsMap.put(0.10, 10); 

     TreeMap<Double, Integer> coinDispenserMap = ref.dispenseChange(0.86, coinsMap); 

     for (Map.Entry<Double, Integer> coin : coinDispenserMap.entrySet()) { 
      System.out.println(coin.getKey() + " : " + coin.getValue()); 
     } 
    } 
} 
+0

您需要比較'雙',而不是'<條目<雙整數>>' –

+0

謝謝。有用!! – Sekhar

回答

2

你比較的類型是Entry<Double, Integer>這需要一個超強型地圖的主要類型,這是Double的。由於Entry<Double, Integer>不是Double的超級類型,所以constructor can't be matched

相反,嘗試:

Map<Double, Integer> coinsMap = 
    new TreeMap<Double, Integer>(new Comparator<Double>() { 
     public int compare(Double coin1, Double coin2) { 
      return (coin2.compareTo(coin1)); 
     } 
    }); 

此外,對於位的風格,你可能要考慮宣佈coinsMap作爲Map<Double, Integer> coinsMap = new TreeMap<>()像我一樣在上面的代碼段。查看Josh Bloch的超棒書籍Effective Java 2nd Ed.(第4章與此處相關),以獲得關於Java的大量建議。

+0

感謝您的建議! – Sekhar

4

試試這個:

Comparator<Double> comparator = Double::compare; 
Comparator<Double> reverseComparator = comparator.reversed(); 
Map<Double,Integer> reversedMap = new TreeMap(reverseComparator); 
相關問題