How to Use if/else Logic in Java 8 Streams

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.

Related posts:

Java Program to Check whether Directed Graph is Connected using DFS
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Compute DFT Coefficients Directly
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Validate email address exists or not by Java Code
Java Program to implement Dynamic Array
Tính kế thừa (Inheritance) trong java
Java Program to Implement Singly Linked List
Introduction to Spring Security Expressions
Check If a File or Directory Exists in Java
Java Program to Implement Bloom Filter
Java Program to Construct an Expression Tree for an Infix Expression
Bootstrapping Hibernate 5 with Spring
Java Program to Implement Extended Euclid Algorithm
Java Program to Implement Repeated Squaring Algorithm
Java Program to Implement Expression Tree
Introduction to Spliterator in Java
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Tìm hiểu về Web Service
Java Program to Find the Mode in a Data Set
Java Program to Implement Sorted Circular Doubly Linked List
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
How to Remove the Last Character of a String?
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Convert Time to Milliseconds in Java
So sánh HashMap và Hashtable trong Java
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Java Program to Represent Graph Using Incidence Matrix
Java Program to Compute Determinant of a Matrix
New Features in Java 15