Generate odd numbers in range

This example will generate odd numbers from a given range. In the snippets below all odd numbers between 1 and 10 will be displayed.

Java 8

The Intstream.rangeClosed will return a range from 1 to 10. Next, a lambda expression will be used to create a java predicate that will return true if the number is odd. Passing it to IntStream.filter it will return all odd numbers for the given range.

@Test
public void generate_odd_numbers_in_range_java8() {

    Set<Integer> oddNumbers = IntStream.rangeClosed(1, 10)
            .filter(n -> n % 2 != 0).boxed().collect(Collectors.toSet());

    logger.info(oddNumbers);

    assertThat(
            oddNumbers,
            contains(new Integer(1), new Integer(3), new Integer(5),
                    new Integer(7), new Integer(9)));
}

Output

[1, 3, 5, 7, 9]

Google Guava

Using guava we will create a ContiguousSet passing in a Range from 1 to 10. We then will pass a guava predicate that will return true if the given number is odd to the Iterables.filter method to return all odd numbers within the range.

@Test
public void generate_odd_numbers_in_range_guava() {

    Set<Integer> set = ContiguousSet.create(Range.closed(1, 10),
            DiscreteDomain.integers());

    Iterable<Integer> oddNumbers = Iterables.filter(set,
            new Predicate<Integer>() {
                @Override
                public boolean apply(Integer input) {
                    return input % 2 != 0;
                }
            });

    logger.info(oddNumbers);

    assertThat(
            oddNumbers,
            contains(new Integer(1), new Integer(3), new Integer(5),
                    new Integer(7), new Integer(9)));
}

Output

[1, 3, 5, 7, 9]