user3815000 user3815000 - 2 years ago 53
Java Question

What is the best way to find what range a number is in?

I am working on a discount requirement, where the user should be given discount based on his order amount.

For example,

Order 1000 to 5000 items - give 10% discount

Order 5000 to 10000 items - give 15% discount

Order 10000 to 15000 items - give 20% discount

These are the details I have in my database.

What is the best way to find the discount percent based on my order amount. I have tried setting these in a List of object and iterate them and find in what range it belongs and then get that percent.

But this seems to be a long approach. Please let me know if there is any better approach than this.

Answer Source

This is my Java solution. Totally agree if you want to do it direct with SQL. But either way, here's some codez! :)

I would use a LinkedHashMap of key "Amounts" with value "Discounts". It's Linked so that it maintains order when you iterate over it, from highest to lowest. If your value is >= the iterated key Amount, apply the value Discount and break out of the loop.

Map<Integer,Integer> map = new LinkedHashMap<>();

public void discount() {


private int discount(int value) {
    for (Map.Entry<Integer,Integer> entrySet : map.entrySet()) {
        if (value >= entrySet.getKey()) {
            return entrySet.getValue();
    return 0;

Results… (it assumes that anything above 10000 is 20%)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download