Get Predecessor Key from Map Using Java

Get Predecessor Key from Map Using Java

I have a map in this

    TreeMap<Integer, Float> matrixMap = new TreeMap<Integer, Float>();

Results in

{12=0.4, 24=0.63, 36=0.86, 48=1.12, 60=1.39, 72=1.67, 84=1.98, 96=2.31, 108=3.3, 120=3.84, 132=4.4, 144=5.0, 156=5.62, 168=6.28, 180=6.97, 192=7.34, 
204=7.74, 216=8.15, 228=8.07, 240=8.33}

Now, I want fetch a value of a key 25. Ideally 25 is not available in the result. So, I want to get values of 24 & 36.

duration  = 25

I'm able to get the value of 36, but how can I get the predecessor of 36.

for(Map.Entry<Integer, Float> entry : matrixMap.entrySet()) {
    if(duration  < entry.getKey())
    {
        max = entry.getValue();
        break;
    }

}

How to get immediate predecessor value too(24 key in this case)?

Any ideas

2 Answers

To get the value of the first key >= 25:

matrixMap.tailMap(25).values().next()

or:

matrixMap.get(matrixMap.tailMap(25).firstKey())

To get the value of the first key <= 25:

matrixMap.get(matrixMap.headMap(25).lastKey())

I've solved using the following way.

int above = matrixMap.ceilingKey(duration);
int below = matrixMap.floorKey(duration);
logger.info("above="+above+", below="+below);
min = insuranceMatrixMap.get(below);
max = insuranceMatrixMap.get(above);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.