Is Guava possible to build range with two conditions as "between"?

Issue

i’m struggling with making range conditions to evaluate values.
For checking values per symbol, I have made switch condition to generate sentence for evaluating values flexibly.

Is below code valid for checking values? (e.g. 300 <= value <= 500).
I have tried a few times, but it was not possible to make range.
(If those method are not effective, i would change them to .closed etc.)

Thanks!

public void symbolToRange(RangeSet<Integer> rangeSet, String symbol, int targetNum) {
    switch (symbol) { // <, <=, =, >=, >
        case ">":
            // targetNum < value
            rangeSet.add(Range.greaterThan(targetNum));
            break;
        case ">=":
            // targetNum <= value
            rangeSet.add(Range.atLeast(targetNum));
            break;
        case "<":
            // targetNum > value
            rangeSet.add(Range.lessThan(targetNum));
            break;
        case "<=":
            // targetNum >= value
            rangeSet.add(Range.atMost(targetNum));
            break;
        case "=":
            rangeSet.add(Range.singleton(targetNum));
            break;
    }
}

Solution

I would have the function return a Range instead of adding to a RangeSet, and throw an exception on an invalid symbol:

public static Range<Integer> symbolToRange(String symbol, int targetNum) {
    switch (symbol) { // <, <=, =, >=, >
        case ">":
            // targetNum < value
            return Range.greaterThan(targetNum);
        case ">=":
            // targetNum <= value
            return Range.atLeast(targetNum);
        case "<":
            // targetNum > value
            return Range.lessThan(targetNum);
        case "<=":
            // targetNum >= value
            return Range.atMost(targetNum);
        case "=":
            return Range.singleton(targetNum);
        default:
            throw new IllegalArgumentException("Invalid symbol: " + symbol);
    }
}

Other than those changes your function seems fine.

Answered By – dimo414

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.