Numeric Ranges Example

This example will demonstrate how produce a numeric range in java 8. A range is set of data between the smallest and largest values. Similar to guava ranges but not yet as powerful, java 8 numerics stream IntStream and LongStream have two static methods available to help generate ranges: "range" and "rangeClosed".

Range will return an ordered stream from start inclusive to a end exclusive. What this means is if you had a start of 1 and end of 10, the numbers return would be 1 - 9. RangeClosed will return an ordered stream from start inclusive to a end inclusive. This means is if you had a start of 1 and end of 10, the numbers return would be 1 - 10.

Range

@Test
public void instream_range() {

    Set<Integer> range = IntStream.range(1, 10).boxed()
            .collect(Collectors.toSet());

    logger.info(range);
}

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

RangeClosed

@Test
public void instream_range_closed() {

    Set<Integer> range = IntStream.rangeClosed(1, 10).boxed()
            .collect(Collectors.toSet());

    logger.info(range);
}

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]