Java Dailly Tip: How to check if an integer is in a given range?

Java Dailly Tip: How to check if an integer is in a given range?

Searching for a range within a given range does not seem difficult, yet we got the question of how to do it quickly and efficiently. Java allows you to do this in many ways. We've covered a few below.

Problem

I have a code like this and I want to know if a number is in the range:

if (i> 0 && i <100)

And I'm looking for something more elegant.

Solution

Personally, I find your code very elegant and efficient. But if you are looking for something that is less efficient but easier to read because you want to hide the loop, we basically have several solutions.

Solution one is to use the Math library:

Math.max(0, i) == Math.min(i, 100)

The second solution is to use the commons-lang library and write the following:

Range  numberRange = Range.between (0, 100);
if (myRange.contains(100)) {
    // do something
}

Another solution is to use stream:

if (IntStream.rangeClosed(0,100) .boxed(). collect(Collectors.toList()). contains (i))

You can also use ValueRange.of ():

int value = 10;
return ValueRange.of(0,100).isValidIntValue(value);

Using guava you have access to the Range class:

import com.google.common.collect.Range;

Range open = Range.open(0, 100);
System.out.println(open.contains(0)); // false

And using Spring you can do it like this:

range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.

Share this Post