×

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

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.