Generate numbers from range

This example will generate a sequential list of numbers from 20 to 30 using java 8 and guava.

Java 8

Using the IntStream.rangeClosed we will create a range of numbers between 20 and 30.

Note: You can also create a range using the LongStream.range.

@Test
public void range_sequential_numbers_java8() {

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

    logger.info(range);

    assertTrue(range.size() == 11);
}

Output

20
21
22
...
28
29
30

Google Guava

Using Guava ContiguousSet class, you can create a set of values by passing in a specified Range of numbers.

@Test
public void range_sequential_numbers_guava() {

    Range<Integer> range = Range.closed(20, 30);

    Set<Integer> ranges = ContiguousSet.create(range,
            DiscreteDomain.integers());

    logger.info(ranges);

    assertTrue(ranges.size() == 11);
}

Output

20
21
22
...
28
29
30