I have a piece of code with which I am trying to sort the keys in the TreeMap
in descending order because when I just use the TreeMap
, it sorts based on keys, which are in ascending order. The I am getting error is:
No Suitable Constructor found for TreeMap.
What's wrong here?
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());
}
}
}
Your comparator's type is Entry<Double, Integer>
which needs to be a super-type of the map's key type, which is Double
. Since Entry<Double, Integer>
isn't a super-type of Double
, the constructor can't be matched.
Instead, try:
Map<Double, Integer> coinsMap =
new TreeMap<Double, Integer>(new Comparator<Double>() {
public int compare(Double coin1, Double coin2) {
return (coin2.compareTo(coin1));
}
});
Also, for a bit of style, you might want to consider declaring coinsMap
as Map<Double, Integer> coinsMap = new TreeMap<>()
as I did in the code snippet above. Check out Josh Bloch's awesome book Effective Java 2nd Ed. (chapter 4 is relevant here) for great advice on Java.