Number within range

This example will will check if a number is between a range of numbers using java 8 and guava.

Java 8

Using java 8 LongStream, a specialized stream for dealing with primitive longs, we will call LongStream.range passing a start value of 1 and an end value of 10 to create a range between 1 and 10. Then checking if the number four is within the range by calling Stream.filter and passing in a predicate created from a lambda expression.

@Test
public void number_between_java8() {

    OptionalLong containsValue = LongStream.range(1, 10)
            .filter(p -> p == 4).findAny();

    assertTrue(containsValue.isPresent());
}

Google Guava

Guava Range class is used to create boundaries around span of values, in this case 1 - 10. By calling the Range.contains method we are able to check if the number 4 is between 1 and 10.

@Test
public void number_between_guava() {

    boolean containsValue = Range.open(1, 10).contains(new Integer(4));

    assertTrue(containsValue);
}