EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Java Stream Filter

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Java Tutorial » Java Stream Filter

Java Stream Filter

Introduction to Java Stream Filter

Stream.filter() is a method in Java we use while working with streams. It traverses through all the elements present and removes or filters out all those elements that are not matching with the specified condition through a significant argument. This is basically an operation that takes place in between the stream interface. The function returns an output stream having the elements of the input stream matching the given conditions.

The argument passed with the filter() will be a stateless predicate and applies to each and every element to identify if it should be included or not. We can pass lambda expression also through this since the predicate falls under the functional interface category. The output contains a new stream that can be used for any other operations relevant to any stream.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

Stream<T> filter(Predicate<? super T> condition)d

Predicate represents a functional interface and shows the condition we use to filter out elements that do not match the stream.

Examples to Implement Java Stream Filter

Let us undertake a few of examples to understand the functionality of the Java stream() function.

Example #1

Code:

import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
arr.stream()
.filter(i -> i % 3 == 0)
.forEach(System.out::println);
}
}

Output:

random numbers

Explanation: This is a very basic and simple example that shows how to use the java stream filter function. In this example, we are declaring an array of random numbers and assigning them to a List. Then we are using the stream filter to filter out all those elements in the given array that satisfy the condition given, i.e. all the numbers in the array that gives a modulus of 3 as 0 are filtered and displayed in the output.

Popular Course in this category
Java Training (40 Courses, 29 Projects, 4 Quizzes)40 Online Courses | 29 Hands-on Projects | 285+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.8 (9,005 ratings)
Course Price

View Course

Related Courses
JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes)jQuery Training (8 Courses, 5 Projects)Free Java Online CourseJavaFX Training (1 Courses)

Example #2

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> arr = Arrays.asList(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
Predicate<Integer> condition = new Predicate<Integer>()
{
@Override
public boolean test(Integer i) {
if (i % 4 == 0) {
return true;
}
return false;
}
};
arr.stream().filter(condition).forEach(System.out::println);
}
}

Output:

first declaring

Explanation: In this example, we are first declaring an input array consisting of a random set of numbers and assigning them a list. Here we are also showing how to use and declare predicate along with stream filter function by first creating an object of the same of the name condition. Then a class of the name test having an input parameter of integer I am created where we are checking the modulus of  4 of the given array. This function returns a boolean value of true if modulues of 4 return 0 and false otherwise. By taking this return value, the stream function is then used to fetch the elements from the array whose condition is true.

Example #3

Code:

import java.util.*;
public class Example {
public static void main(String[] args) {
//Array creation
List<String> arr1 = Arrays.asList("trial", "simple", "node");
//Calling usingFiltOutput function
List<String> op = usingFiltOutput(arr1, "node");
//for loop to print array
for (String arr : op) {
System.out.print(arr);
System.out.print("\n");
}
}
private static List<String> usingFiltOutput(List<String> arr2, String filter) {
List<String> op = new ArrayList<>();
for (String arr1 : arr2) {
if (!"node".equals(arr1)) {
op.add(arr1);
}
}
return op;
}
}

Output:

filtering of array elements

Explanation: In the above example, we are showing the filtering of array elements where we are filtering the element “node” by using the stream filter method

Example #4

Code:

import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Car> listCar = new ArrayList<>();
listCar.add(new Car("Maruti", 350000));
listCar.add(new Car("Toyota", 400000));
listCar.add(new Car("Mahindra", 500000));
listCar.add(new Car("Honda", 600000));
// displaying all cars with cost more than 4lakh
listCar.stream().filter(c -> (c.getID() > 400000))
.forEach(c -> System.out.println(c.getCompany()));
}
}
class Car {
private String company;
private int ID;
public Car() {
}
public Car(String n, int a) {
this.company = n;
this.ID = a;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}

Output:

Java Stream Filter - 4

Explanation: In this example, we shall see a kind of a real-time application where the list of different companies of cars and their basic cost has been assigned to an array list as shown. Then we are defining a few methods below to fetch the individual values from the array list. getcost method is used to get the cost of that particular car, and getCompany is used to get the company name from the input array list. Then in the main function, we are using the Java stream filter function to fetch only those car company names whose approximate cost falls above Rs.400000.

Example #5

Code:

import java.util.*;
import java.util.stream.Collectors;
class Example{
int pro_id;
String pro_name;
float pro_cost;
public Example(int pro_id, String pro_name, float pro_cost) {
this.pro_id = pro_id;
this.pro_name = pro_name;
this.pro_cost = pro_cost;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Example> productsList = new ArrayList<Example>();
//Here we are listing the products
productsList.add(new Example(1,"Shirt",1500f));
productsList.add(new Example(2,"Long Sleeve Top",1000f));
productsList.add(new Example(3,"Crop Top",1600f));
productsList.add(new Example(4,"Jeans",2100f));
productsList.add(new Example(5,"Skirt",1800f));
List<Float> pricesList = productsList.stream()
.filter(p ->p.pro_cost> 1500)
.map(pm ->pm.pro_cost)
.collect(Collectors.toList());
System.out.println(pricesList);
}
}

Output:

Java Stream Filter - 5

Explanation: In this example, we are first declaring out a few parameters regarding the products of a dress shop, such as product id, name, and cost. And by using the ArrayList, we are adding certain products into it along with its parameters. In the end, by using the java stream filter, we are filtering out a few products whose cost is above Rs.1500. This shows a real-time application of this method.

Conclusion

We saw all the different kinds of combinations with which the Java stream filter can be used to filter out certain elements in the array based on the condition we give. It can also be combined with Java streams, array lists, collections, and many others based on the requirement.

Recommended Articles

This is a guide to Java Stream Filter. Here we discuss an introduction to the Java stream() function with respective examples to understand the functionality. You can also go through our other related articles to learn more –

  1. Finally in Java
  2. Java min()
  3. copy() in Java
  4. Java max()

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Java Tutorial
  • Functions
    • String Functions in java
    • Math Functions in Java
    • Hashing Function in Java
    • Regular Expressions in Java
    • Recursion in Java
    • Java Callback Function
    • Java Call by Value
    • Java Call by Reference
    • HashMap in Java
    • Java String Concatenation
    • Java String Equals
    • Compare two Strings in Java
    • Virtual Function in Java
    • Java newInstance()
    • split() Function in Java
    • trim() Function in Java
    • Replace() Function in Java
    • substring() Function in Java
    • Strictfp in Java
    • String Reverse Function in Java
    • Java String getBytes
    • Java Replace Char in String
    • Shuffle() in Java
    • addAll() in Java
    • FileWriter in Java
    • Java Stream Filter
    • Java FileInputStream
    • replaceAll() in Java
    • repaint in Java
    • copy() in Java
    • Java max()
    • Java min()
    • Java Timestamp
    • Java URLConnection
    • Java StringJoiner
    • Java KeyStore
    • Java InetAddress
    • Java getMethod()
    • swap() in Java
    • Deadlock in Java
    • Range in Java
    • Java Repository
    • Java Dictionary
    • Calculator in Java
    • Mutable String in Java
    • Mutable vs Immutable Java
    • Native Methods in Java
    • StringBuffer Class in Java
    • String Class in Java
    • Java URL Class
    • Java Vector Class
  • Basic
    • What is Java?
    • What is JNDI in Java
    • What is JNI in Java
    • What is Java Interface
    • What is Java SE
    • What is JavaBeans
    • Install JDK
    • Java Programming Language Features
    • Applications of Java
    • Career in Java
    • Versions of Java
    • Java Virtual Machine
    • Java GUI Framework
    • Java Packages
    • Java Package Example
    • Default Package in Java
    • Variables in Java
    • Instance Variable in Java
    • Object in Java
    • Java Commands
    • Iterator in Java
    • Java Booleans
    • Conversion in Java
    • Type Conversion in Java
    • String in Java
    • What is JDK
    • What is JVM
    • What is J2EE
    • RMI Architecture
    • Java Literals
    • Data Types in Java
    • Primitive Data Types in Java
    • Enumset in Java
    • Cheat Sheet Java
    • IntelliJ Cheat Sheet
  • Frameworks
    • Best Java Compilers
    • Frameworks In Java
    • Testing Frameworks for Java
    • Java Monitoring Tool
    • Best Java IDE
    • Java Compilers
    • Java Tools
    • Java Deployment Tools
    • Types of Memory in Java
    • Java References
    • Java Type Inference
    • Java Boolean to String
    • Java String to Float
    • java.net Package
    • Java Formatter
  • Operators
    • Arithmetic Operators in Java
    • Unary Operators in Java
    • Logical Operators in Java
    • Comparison Operators in Java
    • Assignment Operators in Java
    • Java String Operators
    • Conditional Operator in Java
    • Boolean operators in Java
  • Keywords
    • Java Keywords
    • this Keyword in Java
    • Static Keyword in Java
    • Native keyword in Java
    • Throw Keyword in Java
    • Throws Keyword in Java
    • What is public in Java?
    • Private in Java
    • Protected Keyword in Java
    • Final Keyword in Java
  • Control statements
    • Control Statement in Java
    • Else-If Statement in Java
    • Nested if Statements in Java
    • Continue Statement in Java
    • Break Statement in Java
    • Case Statement in Java
  • Loops
    • Loops in Java Programming
    • For Loop in Java
    • While Loop in Java
    • do-while loop in Java
    • For-Each loop in Java
    • Nested Loop in Java
  • Inheritance
    • Inheritance in Java
    • Single Inheritance in Java
    • Multilevel Inheritance in Java
    • Hierarchical Inheritance in Java
    • Hybrid Inheritance in Java
  • Constructor and destructor
    • Constructor and Destructor in Java
    • Constructor in Java
    • Destructor in Java
    • Copy Constructor In Java
    • Static Constructor in Java
    • Private Constructor in Java
  • Array
    • Arrays in Java Programming
    • 2D Arrays in Java
    • 3D Arrays in Java
    • Multidimensional Array in Java
    • Array Methods in Java
    • Print 2D Array in Java
    • Print Array in Java
    • String Array in Java
    • Associative Array in Java
    • Dynamic Array in Java
    • Java Array Iterator
    • Java array.push
    • Sort String Array in Java
  • Sorting
    • Sorting in Java
    • Sorting Algorithms in Java
    • Merge Sorting Algorithms in Java
    • Quick Sorting Algorithms in Java
    • Selection Sort In Java
    • Heap Sort In Java
    • Bubble Sort in Java
    • Merge Sort In Java
    • Quick Sort in Java
    • Insertion Sort in Java
    • Sort String in Java
    • Program for Merge Sort in Java
  • Polymorphism
    • What is Polymorphism
    • Polymorphism in Java
    • Runtime Polymorphism in Java
    • Overloading and Overriding in Java
    • Overloading in Java
    • Method Overloading in Java
    • Function Overloading in Java
    • Overriding in Java
    • Method Overriding in Java
    • Final Keyword in Java
    • Super Keyword in Java
    • instanceOf in Java
    • Java Authenticator
    • Java Alias
  • Collections
    • What is TreeMap in Java?
    • Sorting in Collection
    • Java Collections Class
    • Hashtable in Java
    • Java EnumMap
    • Java LinkedHashMap
    • Reverse Linked List in Java
    • LinkedList in Java
  • Date Time
    • java.util.Date
    • Java Clock
    • Java Instant
    • Java LocalTime
    • Java ZoneId
    • Java ZoneOffset
    • Java varargs
    • Java LocalDate
    • Java OffsetDateTime
    • Java LocalDateTime
    • Java Duration
    • Java DayOfWeek
    • Java Period
    • Timer in Java
    • Java TimeZone
    • Java Date Picker
  • Advanced
    • Methods in Java
    • Serialization in Java
    • Inner Class in Java
    • Anonymous Inner Class in Java
    • Java Stack Methods
    • Java Static Nested Class
    • Synchronized Block in Java
    • Static Synchronization in Java
    • Abstract Class in Java
    • Access Modifiers in Java
    • Non Access Modifiers in Java
    • Bit Manipulation in Java
    • Encapsulation in Java
    • Singleton Class in Java
    • Wrapper Class in Java
    • Nested Class in Java
    • Java Matcher
    • Java Pattern Class
    • Java File Class
    • Final Class in Java
    • Stack Class in Java
    • Anonymous Class in Java
    • StringBuilder Class in Java
    • StringBuffer in Java
    • Java Directories
    • JSON in Java
    • Object Class in Java
    • What is Multithreading in java
    • Java Thread Priority
    • Daemon Thread in Java
    • Java Thread Pool
    • Java ThreadLocal
    • Association in Java
    • Queue in Java
    • Functional Programming in Java
    • ClassLoader in Java
    • Interface in Java
    • Functional Interface in Java
    • Java Queue Interface
    • Collection Interface in Java
    • Object Cloning in Java
    • Java.net URI
    • Java Assertion
    • Vector in Java
    • Applets in Java
    • Template in Java
    • Java Shutdown Hook
    • 2D Graphics in Java
    • Autoboxing and Unboxing in Java
    • Comparable in Java Example
    • Java Annotations
    • Java User Input
    • Serialization in Java
    • Dynamic Binding in Java
    • Java Parse String
    • Java Adapter Classes
    • Immutable Class in Java
    • String Initialization in Java
    • String Manipulation in Java
    • ThreadGroup in Java
    • Java Iterate Map
    • Java IO
    • Java?OutputStreamWriter
    • DataInputStream in Java
    • Java BufferedReader
    • Java BufferedWriter
    • Java BufferedInputStream
    • Java ByteArrayInputStream
    • Java ByteArrayOutputStream
    • Java RandomAcessFile
    • Java PrintStream
    • Java PrintWriter
    • Java URLEncoder
    • Java Scanner Class
    • Java Console
    • Java Runtime class
    • Java Base64
    • Java Base64 Encoding
    • Java Base64?Decode
    • Finalize in Java
    • Java Parallel Stream
    • Java Getter Setter
    • Set Interface in Java
    • How to Connect Database in Java
    • How to Create Webservice in Java
    • Composition in Java
    • BinarySearch() in Java
    • Exception Handling in Java
    • Java NullPointerException
    • Java NoSuchElementException
    • Java ConcurrentModificationException
    • Java ArithmeticException
    • Java IOException
    • Java RuntimeException
    • NumberFormatException in Java
    • Java ArrayIndexOutOfBoundsException
    • Java ClassNotFoundException
    • Java FileNotFoundException
    • Java InterruptedException
    • Finally in Java
    • Java Default Method
    • Java Locale
    • Tuples in Java
    • Java ServerSocket
    • Java Lambda Expressions
    • Java DatagramSocket
    • Java Animation
  • MISc
    • What is Synchronization in Java
    • What is Concurrency in Java
    • What is Design Pattern in Java
    • What is Generics in Java
    • What is API in Java
    • What is a Binary Tree in Java
    • What is Java Garbage Collector
    • What is Java Inheritance
    • Thread Life cycle in Java
    • Object Oriented Programming in Java
    • Java App Development
    • Java Naming Conventions
    • Java hashCode()
    • Java Transient
    • JSTL In Java
    • Comparable in Java 
    • Aggregation in Java
    • EJB in Java
    • @deprecated in Java
    • Java @Inherited
    • @SuppressWarnings in Java
    • Java @Override
  • Programs
    • Patterns in Java
    • Star Patterns in Java
    • Number Patterns in Java
    • Swapping in Java
    • Factorial in Java
    • Fibonacci Series in Java
    • Reverse Number in Java
    • Palindrome in Java
    • Armstrong Number in Java
    • Squares in Java
    • Square Root in Java
    • Special Number in Java
    • Anagram Program in Java
    • Strong Number in Java
    • Random Number Generator in Java
    • Matrix Multiplication in Java
    • Socket Programming in Java
    • Prime Numbers in Java
    • String Comparison in Java
    • Leap Year Program in Java
    • Reverse String in Java
    • Design Patterns in Java
    • Happy Numbers in Java
  • Interview Questions
    • Java Interview Questions
    • Java Inheritance Interview Questions
    • Java EE Interview Questions
    • Java Developer Interview Questions
    • Java Collection Interview Questions
    • Java Interview Question on Multithreading
    • Java String interview question
    • Java Testing Interview Questions
    • Java Multi-threading Interview Questions
    • Multithreading Interview Questions in Java
    • Oops Java Interview Questions
    • Java Spring Interview Questions
    • Data Structure Java Interview Questions
    • Java Web Services Interview Questions

Related Courses

Java Course

JavaScript Certification Course

jQuery Training Course

Java Training Courses

Free Java Training Courses

JavaFX Training

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • 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

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

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

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

EDUCBA

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

Web development, programming languages, Software testing & others

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

Special Offer - Java Course Learn More