×

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression. It is quite useful for a library's collection. It is beneficial to sort through a collection of data, iterate it over it, and extract relevant data. The use of the Lambda expression allows for the implementation of an interface with such a functional interface. Code is saved in large amounts. A lambda expression avoids this problem by allowing the implementation to be provided without redefining the method.

Just the implementation code is written here. Java lambda expressions are considered functions; hence the compiler does not produce a .class file.

If Condition

For each valid input, the lambda function would return a value. If the condition is true in this case, the block will be returned, and if it is false, the block will be returned.

1. The If Condition Combined with Predicates

We can give the condition directly to the filter() procedure as a Predicate if we just want to use "if" logic.

In the example shown, we are determining whether a number is even before printing a message.

ArrayList<Integer>numberList = new ArrayList<>(Arrays.asList(9,8,7,6,5,4));
Predicate<Integer>isEven = i ->i % 2 == 0;
numberList.stream()
.filter(isEven)
.forEach(System.out::println);

2. Consumer Implementation of the "if-else" Condition

In the forEach() function, the "if-else" condition can be implemented as a lambda expression in the form of a Consumer action.

A functional interface called Consumer has a functional method called "void accept(Object)". It stands for an operation that only takes one input argument and produces no output.

In the example provided, if a value is even, a message will be printed; if it's odd, a different message will be printed.

ArrayList<Integer>numberList
    = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
Consumer<Integer> action = i -> {
    if (i % 2 == 0) {
System.out.println("Even number :: " + i); //Or any other user action we want to do
    } else {
System.out.println("Odd  number :: " + i);  //Or any other user action we want to do
    }
};
numberList.stream()
.forEach(action);
  • Instead of just publishing the stream objects to the console, we may do anything with them, such as placing them in two different lists or passing them to other function calls.
  • If necessary, set multiple if-else statements that can be written.
  • Inline lambda expressions can be used to provide the Consumer implementation to the forEach() method.
Arrays.asList(-2, 1, -3, 4, 5, -6,6, 7, 0).stream()
.forEach(
i -> {


          if (i == 0) {
System.out.println("Number is 0");
          } else if (i> 0) {
System.out.println("Positive Number");
          } else {
System.out.println("Negative Number");
          }
        }
    );

3. Conventional if/else Logic Inside of forEach ()

Let's first establish an Integer List, and then inside the Integer stream forEach() method, utilize standard if/else logic:

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);
        }
    });

The Java modulus function is used in our forEach method's if-else logic to determine whether the number is an odd or even value.

4. if/else Logic Combined With a filter()

Second, let's have a look at a more tasteful application that makes use of the Stream filter() technique:

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));

In the example above, we used the Stream filter() function to divide the Integer List into two different Streams, one just for even integers and one for odd integers, in order to apply the if/else logic.

Benefits of the Lambda Expression

  • Less Code: One of the main advantages of using lambda expressions is that there are fewer lines of code to write. We are aware that only a functional interface enables the use of lambda expressions. For instance, since Framework to address is a functional language, lambda expressions are simple to use.
  • Support for parallel and sequential execution through the use of behaviour arguments in methods Java 8's Stream API is used to pass the functions to collection methods. Now, it is up to the collection to decide whether to handle the elements sequentially or concurrently.
  • More Efficiency When doing bulk operations on collections, we can obtain higher efficiency (parallel processing) by leveraging the Stream API as well as lambda expressions. Additionally, rather than using external iteration, lambda expressions make it possible to iterate collections internally.

Related Topics

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.