×

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

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.