I have some constants f.e.:
BigDecimal ceiling1 = new BigDecimal(5);
BigDecimal ceiling2 = new BigDecimal(10);
BigDecimal ceiling3 = new BigDecimal(20);
BigDecimal rate1 = new BigDecimal(0.01);
BigDecimal rate2 = new BigDecimal(0.02);
BigDecimal rate3 = new BigDecimal(0.04);
BigDecimal rate4 = new BigDecimal(0.09);
Now based on a parameter f.e.:
BigDecimal arg = new BigDecimal(6);
I want to retrieve the right rate which is based on this if structure (simplified):
if(arg <= ceiling1) {
rate = rate1;
}else if(arg <= ceiling2) {
rate = rate2;
} else if (arg <= ceiling3) {
rate = rate3;
}else rate = rate4;
So in my example rate should be rate2
But I’m wondering if someone knows a better way to implement this, instead of a bunch of ifs.
Any pointers are welcome!
PS: I know my code isn’t 100% right, just wanted to show the idea
You can store your ceilings as keys in a TreeMap and your rates as values. Then use floorEntry and see also here.
Test: http://ideone.com/VrucK. You may want to use a different representation as you can see in the test it looks ugly(Like Integers for the ceiling). Btw the ugly output comes from the fact that 0.01 is a double which does funny things with decimal representations.
Edit: Suggested cleanup.