## 1. Overview

In this tutorial, we're going to demonstrate how to implement if/else logic with Java 8 Streams.Â As part of the tutorial, we'll create a simple algorithm to identify odd and even numbers.

We can take a look at this article to catch up on the Java 8 Stream basics.

## 2. ConventionalÂ if/else Logic Within forEach()

First of all,Â letâ€™s create an Integer List and thenÂ use conventional if/else logic within theÂ IntegerÂ streamÂ forEach() method:

``````List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

ints.stream()
.forEach(i -> {
if (i.intValue() % 2 == 0) {
Assert.assertTrue(i.intValue() % 2 == 0);
} else {
Assert.assertTrue(i.intValue() % 2 != 0);
}
});``````

Our forEach method contains if-else logic which verifies whether the Integer is an odd or even number using the Java modulus operator.

## 3. if/else Logic With filter()

Secondly, let's look at a more elegant implementation using the Stream filter() method:

``````Stream<Integer> evenIntegers = ints.stream()
.filter(i -> i.intValue() % 2 == 0);
Stream<Integer> oddIntegers = ints.stream()
.filter(i -> i.intValue() % 2 != 0);

evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 == 0));
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 != 0));``````

Above we implemented the if/else logic using the Stream filter() method to separate the Integer List into two Streams, one for even integers and another for odd integers.

## 4. Conclusion

In this quick article, weâ€™ve explored how to create a Java 8 Stream and how to implement if/else logic using the forEach() method.

Furthermore, we learned how to use the Stream filter method toÂ achieve a similar result, in a more elegant manner.

Finally, the complete source code used in this tutorial is availableÂ over on Github.

### Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE