Let's say an integer should be within the range: [0...2147483647]
I want to check whether an integer variable falls within this range. I know it can be accomplished by a simple if-else statement, but is there a more efficient way to check whether it's within the range?
I'd rather not do this:
if (foo >= 0 && foo <= 2147483647)
{
// do something
}
In Java, the Range method is available in IntStream as well as LongStream class. In IntStream class, it helps in returning sequentially ordered values of IntStream in the range mentioned as parameters of the function.
You can do that this way: int[] arr = new int[end - start]; IntStream. range(0, end - start). forEach(i -> arr[i] = i + start);
Use the substring() method to set a range of substring from a string. Let's say the following is our string. String strRange = str. substring(3, 6);
The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can be stored in the byte data type is −(28−1) to (28−1)−1. = −27 to (27) -1. = −128 to 127.
Apache Commons Lang has a Range
class for doing arbitrary ranges.
Range<Integer> test = Range.between(1, 3);
System.out.println(test.contains(2));
System.out.println(test.contains(4));
Guava Range
has similar API.
If you are just wanting to check if a number fits into a long value or an int value, you could try using it through BigDecimal
. There are methods for longValueExact
and intValueExact
that throw exceptions if the value is too big for those precisions.
You could create a class to represent this
public class Range
{
private int low;
private int high;
public Range(int low, int high){
this.low = low;
this.high = high;
}
public boolean contains(int number){
return (number >= low && number <= high);
}
}
Sample usage:
Range range = new Range(0, 2147483647);
if (range.contains(foo)) {
//do something
}
I know this is quite an old question, but with Java 8's Streams you can get a range of int
s like this:
// gives an IntStream of integers from 0 through Integer.MAX_VALUE
IntStream.rangeClosed(0, Integer.MAX_VALUE);
Then you can do something like this:
if (IntStream.rangeClosed(0, Integer.MAX_VALUE).matchAny(n -> n == A)) {
// do something
} else {
// do something else
}
You could use java.time.temporal.ValueRange
which accepts long
and would also work with int
:
int a = 2147;
//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max
ValueRange range = ValueRange.of(0, 2147483647);
if(range.isValidValue(a)) {
System.out.println("in range");
}else {
System.out.println("not in range");
}
If you are checking against a lot of intervals, I suggest using an interval tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With