Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - Check if Double is within range?

Tags:

java

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.

like image 225
gene b. Avatar asked Apr 21 '18 22:04

gene b.


People also ask

How do you check if a value is between a range in Java?

ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.

How do you check if a string contains a double?

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.


1 Answers

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 doubles, 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.

like image 117
Jacob G. Avatar answered Sep 23 '22 14:09

Jacob G.