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 Implement VList
Using Optional with Jackson
Java Program to Implement Caesar Cypher
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Implement the RSA Algorithm
Từ khóa throw và throws trong Java
Working With Maps Using Streams
An Example of Load Balancing with Zuul and Eureka
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Implement the One Time Pad Algorithm
Enum trong java
Java Program to Compare Binary and Sequential Search
How to Replace Many if Statements in Java
Receive email using IMAP
Hướng dẫn Java Design Pattern – Null Object
Hướng dẫn Java Design Pattern – Iterator
HandlerAdapters in Spring MVC
Java Program to Implement CopyOnWriteArraySet API
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Convert a Map to an Array, List or Set in Java
Build a REST API with Spring and Java Config
Java Program to Implement K Way Merge Algorithm
Spring Security OAuth2 – Simple Token Revocation
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Spring Boot - Exception Handling
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Removing all Nulls from a List in Java
LIKE Queries in Spring JPA Repositories
Java Program to Implement Binomial Heap
Mockito and JUnit 5 – Using ExtendWith
Java Program to Implement Fermat Factorization Algorithm