EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Stream Filter
Secondary Sidebar
Java 8 Tutorial
  • Java 8 basic
    • Java 8 forEach
    • Java 8 Documentation
    • Java 8 Method Reference
    • Java 8 List to Map
    • Java 8 Parallel Stream
    • Java 8 Functional Interface
    • Java 8 API
    • Java 8 Lambda
    • Java 8 Comparator
    • Java 8 Group By
    • Java 8 Predicate
    • Java 8 Default Methods
    • Java 8 Thread
    • Java 8 HashMap
    • Java 8 Read File
    • Java 8 OpenJDK
    • Java 8 Stream Filter
    • Java 8 Interface

Java 8 Stream Filter

Introduction to Java 8 Stream Filter

Java 8 Stream Filter is a method used to filter stream elements based on a given predicate. It takes a predicate as an argument and returns a stream that consists of resultant elements. For e.g., if the user wants to get even elements out of the List, it can be done using Stream Filter.

Java 8 Stream Filter

Key Takeaways

  • It provides a filter() method to stream filtered elements on the given predicate.
  • Most stream operations accept params that describe user-specified behavior like lambda expression. To preserve the behavior of behavioral parameters, they must be non-interfering and must be stateless in most cases.
  • Java filter() method is an intermediate operation that reads data from the Stream and returns a new stream once transformed based on given conditions.
  • It takes a predicate as an argument and returns a stream consisting of elements as the resultant.
  • The stream consists of a sequence of objects from a source that supports aggregate operations.

What is Java 8 Stream Filter?

It is an intermediate operation and is lazy; operating this lazy operation does not perform filtering but creates a new stream when traversed, containing elements of the initial Stream that match the predicate.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

It filters data as it is read from and written to a stream. This method is used in functional programming as an intermediate method. Stream Filter returns a stream of elements that match with a given predicate. The predicate is stateless and non-interfering and applicable to each element which determines if it has to be included or not.

Execution of Stream filtering creates a new stream instead of performing filtering, and when it is traversed, it contains initial stream elements matching with a predicate.

Syntax or Signature

Java 8 Stream Filter() method is shown below:

Stream<T> filter(Predicate <? super T> predicate)
  • Stream – Interface
  • T – Type of input to predicate
  • Return type – New Stream

Predicate refers to an argument; it is functional interference so the user can pass lambda expressions.

Parameters and Methods

Parameters involved with the Stream Filter method are the Type of input to predicate and Stream being an interface.

Filter() method is an Intermediate Stream operation; the argument should be a stateless predicate applied to each stream filter element. Predicate being a functional interface, can also pass lambda expressions. The new Stream is generated; hence, the user can apply other stream operations.

Examples of Java 8 Stream Filter()

Given below are the examples mentioned:

Example #1

Stream filter() method applied on List.

Code:

import java.util.*;
public class numDivide {
public static void main(String[] args)
{
List<Integer> listArr = Arrays.asList(2, 5, 16, 30, 10);
listArr.stream()
.filter(number -> number % 4 == 0)
.forEach(System.out::println);
}
}

Output:

Stream filter() method applied on List

Example #2

The below example applies the Stream filter() method on the Stream of strings.

Code:

import java.util.stream.Stream;
public class Alpha {
public static void main(String[] args)
{
Stream<String> streamofAlpha = Stream.of(
"Hello", "yOu", "ArE", "aVaiLaBLe");
streamofAlpha.filter(string -> string.endsWith("e"))
.forEach(System.out::println);
}
}

Output:

Stream filter() method on the Stream of strings

Example #3

Here, we will fetch and iterate the filtered data using Streams filter() and map().

Code:

import java.util.*;
class Student{
int stuid;
String stuname;
int stuage;
public Student(int stuid, String stuname, int stuage) {
this. stuid = stuid;
this. stuname = stuname;
this. stuage = stuage;
}
}
public class FilterStream {
public static void main(String[] args) {
List<Student> studentsList = new ArrayList< Student >();
studentsList .add(new Student (101,"Aarthi",5));
studentsList .add(new Student (102,"Dileep",7));
studentsList .add(new Student (103,"Lucky",4));
studentsList .add(new Student (104,"Suresh",10));
studentsList .add(new Student (105,"Gautam",6));
studentsList .stream()
.filter(age ->age.stuage> 8)
.map(agemap ->agemap.stuage)
.forEach(System.out::println);
}
}

Output:

fetch and iterate the filtered data

Example #4

In this example, we shall fetch filtered data using the Streams filter() method and map() in the form of a list.

Code:

import java.util.*;
import java.util.stream.Collectors;
class Student{
int stuid;
String stuname;
double stumarks;
public Student(int stuid, String stuname, double stumarks) {
this. stuid = stuid;
this. stuname = stuname;
this. stumarks = stumarks;
}
}
public class FilterStream {
public static void main(String[] args) {
List<Student> studentsList = new ArrayList< Student >();
studentsList .add(new Student (101,"Aarthi",50.2));
studentsList .add(new Student (102,"Dileep",73.21));
studentsList .add(new Student (103,"Lucky",30.00));
studentsList .add(new Student (104,"Suresh",98));
studentsList .add(new Student (105,"Gautam",67.3));
List<Double> markList = studentsList.stream()
.filter(marks ->marks.stumarks> 50.0)
.map(marksmap ->marksmap.stumarks)
.collect(Collectors.toList());
System.out.println(markList);
}
}

Output:

Streams filter() method and map()

Example #5

Using Streams Filter() method and collect().

Stream.filter() will filter the List, and the collect() method is used to convert the Stream to a List.

Code:

package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Sample {
public static void main(String[] args) {
List<String> lineString = Arrays.asList("educba", "react", "angular");
List<String> resultant = lineString.stream()
.filter(lstring -> !"react".equals(lstring))
.collect(Collectors.toList());
resultant.forEach(System.out::println);
}
}

Output:

Java 8 Stream Filter to List

Example #6

Filtering by using Custom Predicate.

Code:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Main
{
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
Predicate<Integer> condition = new Predicate<Integer>()
{
@Override
public boolean test(Integer num) {
if (num % 2 == 0) {
return true;
}
return false;
}
};
list.stream().filter(condition).forEach(System.out::println);
}
}

Output:

Filtering by using Custom Predicate

Conclusion

Hereby, we shall conclude the topic “Java 8 Stream Filter”. We have seen what Java 8 stream filter and its signature. I have also gone through various key terminologies involved with filter() methods such as Stream, Predicate, etc. I have executed a few examples that are easier to understand as a beginner.

Recommended Articles

This is a guide to Java 8 Stream Filter. Here we discuss the introduction, what are Java 8 stream filters, parameters and methods, and examples. You can also look at the following articles to learn more –

  1. Java 8 OpenJDK
  2. Java 8 Read File
  3. Java 8 Memory Model
  4. Java 8 Group By
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more