I know that for Integers, Java 8 has IntStream which allows you to generate ranges and check them, e.g.
IntStream range = IntStream.rangeClosed(5,10);
range.anyMatch(x -> x == 4);
My problem is that I have Double ranges, defined as:
Light [0, 3.0)
Moderate [3.0, 6.0)
Vigorous >= 6.0
The variable being checked against these ranges is a double val
. I was just wondering if Java 8 has any convenient solutions for this. I don't want to use elaborate if/else
trees for various reasons.
ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.
Using the parseDouble() method Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.
As pkpnd stated in their comment, there is a known difference between one int
and the next (ex. 4
and 5
are one integer apart). However, how far apart are two arbitrary double
s, an ulp?
One suggestion that I have to emulate a range is to use a NavigableMap
:
enum Range {
LIGHT, MODERATE, VIGOROUS, UNKNOWN
}
NavigableMap<Double, Range> map = new TreeMap<>();
map.put(Double.NEGATIVE_INFINITY, Range.UNKNOWN);
map.put(0D, Range.LIGHT);
map.put(3D, Range.MODERATE);
map.put(6D, Range.VIGOROUS);
System.out.println(map.floorEntry(4D).getValue());
Output:
MODERATE
You're free to handle out-of-range values however you'd like, as well a Double.NaN
.
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