如何自定义TreeMap以降序排序键?

时间:2016-04-09 02:58:18

标签: java sorting 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());
        }
    }
}

2 个答案:

答案 0 :(得分:4)

试试这个:

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

答案 1 :(得分: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的精彩建议。