Search code examples
javatreehashmaptreemap

Navigable Maps: lowerKey() method on BigDecimal or NextKey?


Suppose I have a tree map in reverse order (descending)

TreeMap <BigDecimal, Integer> m = new TreeMap <>(Comparator.reverseOrder);

Suppose I have the keys (in BigDecimal)

(100.00, 75.50, 50.50)

And if I call the method (with big decimal parameter)

m.lowerKey(100.00)

It will output null. I guess this has to do with the comparison of BigDecimals, however how could I make it to output 75.50 instead? Or more simply, is it possible to get the next key given the current key, since it is ordered?

One possible solution is to use Double as keys instead. However I am dealing with money and conversion between them sound a bit tedious.(Plus I am doing some arithmetic so double is error-prone)

Note: No lambdas / functional constructs and external libraries!


Solution

  • how could I make it to output 75.50 instead?

    You defined your TreeMap to use a reversed comparator so to it 100.00 is lower than 75.50. That means you'd need to use higherKey() here.

    Is it possible to get the next key given the current key, since it is ordered?

    Yes it is but you need to be aware of the ordering. If you provided a comparator this will define the ordering and what the TreeMap deems lower or higher. Also note that the comparator also has influence on duplicate detection, i.e. any keys that would be equal due to the comparator would be duplicates to the TreeMap.