Make Selenium Easy

How To Filter List Using Java Stream API?

Introduction

Stream API feature was introduced in Java 8 but it is still confusing for many and also many have not even used it a single time. I will try to explain Java Stream concepts with simple examples in Learn Stream API in Java with Examples series.

In this post, we will learn to filter a Java List using Stream APIs i.e. filter() method.

YouTube Tutorials

If you want to learn from a video tutorial then please refer to the below video –

Filter Java List List Without Stream API

We may be required to filter a Java List based on one or multiple conditions. We need to iterate the array and apply filter conditions. Let’s write a very simple program to filter a list.

Java Program

Output

All subjects : [Java, Functional Testing, Performace Testing, Selenium Testing, Mongo DB]
All testing subjects : [Functional Testing, Performace Testing, Selenium Testing]

Filter Java List List With Stream API

Stream interface provides a method filter() which helps you to filter a list based on condition/s. The filter() method takes a Predicate which is a functional interface. We can use the lambda expressions to write shorter code.

  1. Get a sequential stream of List using stream() method.
  2. Call filter() method with the condition on stream.
  3. Collect results into a List.

Java Program

Output

All subjects : [Java, Functional Testing, Performace Testing, Selenium Testing, Mongo DB]
All testing subjects : [Functional Testing, Performace Testing, Selenium Testing]

You can use multiple conditions as below –

.filter(ele -> ele.contains(“Testing”) && ele.contains(“Selenium”))

GitHub Repo Link

https://github.com/amod-mahajan/MSE_LearnJavaStreamsWithExamples.git

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

How To Filter List Using Java Stream API?

by Amod Mahajan time to read: 2 min
0
%d bloggers like this: