Generate even numbers in range

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

Java 8

Using an Intstream we will create a range of numbers from 1 to 10. Next, using a lambda expression to create a java predicate that will return true if the number is even. Passing it to IntStream.filter it will return all even numbers for the given range.

@Test
public void generate_even_numbers_in_range_java8() {

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

    logger.info(evenNumbers);

    assertThat(
            evenNumbers,
            contains(new Integer(2), new Integer(4), new Integer(6),
                    new Integer(8), new Integer(10)));
}

Output

 2
 4
 6
 8
 10
 

Google Guava

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

@Test
public void generate_even_numbers_in_range_guava() {

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

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


    assertThat(
            evenNumbers,
            contains(new Integer(2), new Integer(4), new Integer(6),
                    new Integer(8), new Integer(10)));
}

Output

2
4
6
8
10