In this tutorial, we are going to learn “How to use ‘If/Else’ conditional logic in Java 8 Streams”. We are going to achieve that with the help of Predicate and Consumer Interfaces.  

Check out: takeWhile / dropWhile operations in Java 9 Stream

Iterate & ofNullable in Java 9 with Examples...!!! Share on X

In this tutorial, we are going to cover below topics:

  1. ‘If/Else’ condition using Consumer Interface
  2. ‘If’ condition using Predicate Interface with Filter method

1. ‘If/Else’ condition using Consumer Interface

‘If/Else’ logical condition can be supplied as a lambda expression using Consumer Interface in the forEach() function. It is a functional interface and has accept(Object) as the functional method. Consumer Interface represents an operation that accepts a single input argument and returns no result.

Example

In this example, we are trying to check whether the number is Even or Odd and to do that, we are using the Consumer Interface. 

Output:

2. ‘If’ condition using Predicate Interface with Filter method

Here, we are going to use Predicate Interface which returns the boolean value. Then we will pass the output(boolean value) of the Predicate to the filter method which basically returns the stream elements that matches the given predicate. 

Example

In this example, we are trying to checking Even/Odd numbers using Predicate Interface with ‘filter’

Output:

I hope above examples could help you to understand how to implement logical conditions (if/else) using Functional Interfaces.

Cheers!

Iterate & ofNullable in Java 9 with Examples...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak