$show=/label

Java 8 Streams if else logic

SHARE:

A quick guide to if-else conditions in java 8 with streams.

1. Overview

In this tutorial, We'll learn how to use if/else statements in java 8 streams.

If you are new to the java 8 stream,  It is recommended to read the in-depth on the basics of java 8 streams.

First, we will see the simple to find the even numbers from the given list of numbers.

Next, we will write the java 8 examples with the forEach() and streams filter() method.

Java 8 Streams if else logic



2. Java Conventional If Else condition


In the below example, a List with the integers values is created. Next, we run the for loop from index 0 to list size - 1. Take each index value and check the number is even or not using if-else condition.

If the if-condition is satisfied then it is an even number else it is an odd number.

Example 1
package com.javaprogramto.java8.streams.filter.ifelse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IfElseExample {

	public static void main(String[] args) {

		List<Integer> numbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100);

		List<Integer> evenList = new ArrayList<>();
		List<Integer> oddList = new ArrayList<>();

		for (int index = 0; index < numbersList.size(); index++) {
			if (numbersList.get(index) % 2 == 0) {
				evenList.add(numbersList.get(index));
			} else {
				oddList.add(numbersList.get(index));
			}
		}

		System.out.println("Even numbers list - " + evenList);
		System.out.println("Odd numbers list - " + oddList);
	}

}

Output
Even numbers list - [10, 20, 24, 16, 100]
Odd numbers list - [13, 15, 17]

3. Java 8 Streams If Else condition In forEach()

In java 8, stream api is added with the forEach() method and inside this, we can add the if-else conditions.

But, forEach() is called on the streams.

Example 2
package com.javaprogramto.java8.streams.filter.ifelse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8StreamForEachExample {

	public static void main(String[] args) {

		List<Integer> numbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100);

		List<Integer> evenList = new ArrayList<>();
		List<Integer> oddList = new ArrayList<>();
		numbersList.stream().forEach(number -> {
			if (number % 2 == 0) {
				evenList.add(number);
			} else {
				oddList.add(number);
			}

		});

		System.out.println("Even numbers list - " + evenList);
		System.out.println("Odd numbers list - " + oddList);
	}
}

Output
Even numbers list - [10, 20, 24, 16, 100]
Odd numbers list - [13, 15, 17]




4. Java 8 Streams If Else condition


By using traditional for loop and if-else conditions, we could get the odd and even numbers into separate lists but we had to write many lines of code.

But, with the new concepts of java 8 streams, the full logic can be reduced to two lines to get the separate even and odd numbers lists.

Use the java 8 stream filter() method to get the equivalent functionality of the traditional if condition.

Example 3

look at the below code how the filter() method takes the predicate functional interface. 

The Predicate is the functional interface that does the job of if condition. But this predicate statement should be passed to the filter() method so that the predicate function is evaluated.

package com.javaprogramto.java8.streams.filter.ifelse;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8StreamIfElseExample {

	public static void main(String[] args) {

		List<Integer> numbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100);

		List<Integer> evenList = numbersList.stream().filter(number -> number % 2 == 0).collect(Collectors.toList());
		List<Integer> oddList = numbersList.stream().filter(number -> number % 2 == 1).collect(Collectors.toList());

		System.out.println("Even numbers list - " + evenList);
		System.out.println("Odd numbers list - " + oddList);
	}
}


Output
Even numbers list - [10, 20, 24, 16, 100]
Odd numbers list - [13, 15, 17]

We can see the same output as in section 2. 

Java 8 streams syntax completely reduces the boilerplate code.


4. Java 8 Streams Multiple If conditions


Actually, we can call the filter() multiple times on the streams. So, if you have multiple conditions in your use case, either you can add all conditions in the single predicate statement or you can make calls to the filter() method as many times you want.


Example 4

The below example get the even numbers that are greater than 20.
Here, we have two conditions - first one is number is greater than 20 and second is checking the even number.

package com.javaprogramto.java8.streams.filter.ifelse;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8StreammultipleIfExample {

	public static void main(String[] args) {

		List<Integer> numbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100);

		List<Integer> evenList = numbersList.stream()
						.filter(number -> number > 20)
						.filter(number -> number % 2 == 0)
						.collect(Collectors.toList());

		System.out.println("Even numbers list - " + evenList);
	}
}

Output
Even numbers list - [24, 100]


6. Conclusion


In this article, we've seen how to use if-else and multiple if conditions with java 8 streams.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Streams if else logic
Java 8 Streams if else logic
A quick guide to if-else conditions in java 8 with streams.
https://blogger.googleusercontent.com/img/a/AVvXsEjHanM9q8SX7NrZYSV81CIQMQ0C0HRNy92CoBKz3WA-32PBAhr7injPHrYoIjR1g1YbK8UF0pTEJF-WBDkZCaNuyrYHEAzw2Q3m5R7DzC_7bQAz3ahqEvN153D-rbxlMKhELOF3q0Z00bhVgyhGoUbG11j0YG8PHTwXFUA5B3SIE85AeU3Yux0Jd6ux=w400-h215
https://blogger.googleusercontent.com/img/a/AVvXsEjHanM9q8SX7NrZYSV81CIQMQ0C0HRNy92CoBKz3WA-32PBAhr7injPHrYoIjR1g1YbK8UF0pTEJF-WBDkZCaNuyrYHEAzw2Q3m5R7DzC_7bQAz3ahqEvN153D-rbxlMKhELOF3q0Z00bhVgyhGoUbG11j0YG8PHTwXFUA5B3SIE85AeU3Yux0Jd6ux=s72-w400-c-h215
JavaProgramTo.com
https://www.javaprogramto.com/2021/12/java-8-streams-if-else.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/12/java-8-streams-if-else.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content