Java Stream API: Filtering Made Easy with Filter Method
Java Stream Filter
In Java Stream API, the filter method is used to filter
elements based on a given predicate . Its primary purpose is to process a
stream of data and selectively retain elements that satisfy a specified
condition, while discarding those that do not.
The
key purposes and benefits of using the filter method:
Selective
Element Processing: filter allows you to selectively process elements of
a stream based on a condition defined by a predicate.
Predicate
Flexibility: The predicate passed to filter can be as simple or as
complex as needed. It can involve simple conditions (like comparing values) or
more intricate checks (such as evaluating multiple fields of an object).
Stream
Pipeline Composition: filter is typically used as part of a stream pipeline
in combination with other stream operations (map, reduce, etc.). This allows
for concise and expressive code that performs complex data transformations
efficiently.
Efficiency: Stream
operations are designed to be processed lazily and are often optimized by the
underlying implementation. Filtering elements early in a pipeline can reduce
the amount of data that needs to be processed by subsequent operations,
potentially improving performance.
Readability
and Maintainability: Using filter can make your code more readable by
clearly expressing the criteria for including elements in the stream. It also
contributes to code maintainability, as the filtering logic is encapsulated within
the predicate.
Practical
Examples and Best Practices
Check out my GitHub repository here: Stream Filter
01.Example
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
class SingleFilterOperation
{
public
static void main(String[] args) {
// Create a list of integers using Arrays.asList
List<Integer> numbersList= Arrays.asList(100,101,102,103,104,105);
// Stream operations on numbersList
numbersList.stream()
// Filter operation: Keep only elements that are even (n % 2 == 0)
.filter(n -> n%2
== 0)
// For each filtered element, print it to the console
.forEach(System. out::println) ;
}
}
Explanation:
1. Imports and Class Declaration:
·
import
java.util.Arrays;: Imports the ‘Arrays’ utility class which provides
various methods for manipulating arrays (like ‘asList’).
·
import
java.util.List; : Imports the ‘List’ interface from the ‘java.util’ package.
·
import
java.util.ArrayList; : Imports the ‘ArrayList’ class from the ‘java.util’
package.
·
class
SingleFilterOperation { ... } : Defines a class named ‘SingleFilterOperation’.
2. Main Method (‘public
static void main(String[] args) { ... }’):
·
This is the entry point of the program, where
execution begins.
3. List Initialization:
List<Integer> numbersList =
Arrays.asList(100, 101, 102, 103, 104, 105);
·
Creates a fixed-size list (‘numbersList’)
containing integers using ‘Arrays.asList’, which converts the provided elements
into a ‘List’.
4. Stream Pipeline:
·
numbersList.stream():
Converts the `List` into a stream of integers (‘Stream<Integer>’).
·
.filter(n
-> n % 2 == 0) : Filters the stream to keep only those elements (`n`)
which are even. Here, ‘n % 2 == 0’ checks if ‘n’ is divisible by 2 (i.e., ‘n’
is even).
·
.forEach(System.out::println):
For each element that passes the filter, prints it to the console using the
method reference System.out::println. This method reference is shorthand for a
lambda expression that takes an argument (`n`) and calls System.out.println(n).
Execution Flow:
·
The ‘numbersList’ is converted into a stream.
·
The ‘filter’ operation processes each element in
the stream and retains only even numbers.
·
The ‘forEach’ operation then prints each
filtered number to the console.
Output:
These are the even numbers from the ‘numbersList’ that
satisfy the condition ‘n % 2 == 0’.
Summary:
This Java program demonstrates the use of streams (Stream API)
for processing a list of integers (numbersList). It showcases filtering
elements based on a condition (n % 2 == 0 for even numbers) and performing an action
(printing to console) on each filtered element.
02.Example
import java.util.Arrays;
import java.util.List;
public class MultipleFilterOperation {
public static void main(String[] args) {
// Create a list of strings using Arrays.asList
List<String> name = Arrays.asList("Java","C++","C","Python","Assembly","PHP");
// Stream operations on the 'name' list
name.stream()
// Filter operation: Keep only strings with length greater than 1 and less than 4
.filter(str-> str.length()>1 && str.length()<4)
// For each filtered string, print it to the console
.forEach(System.out::println);
}
}
Explanation:
1.Imports:
·
import
java.util.Arrays; : Imports the Arrays utility class for working with
arrays.
·
import
java.util.List; : Imports the List interface from the java.util
package.
2.Class Declaration:
·
public class
MultipleFilterOperation { ... }: Defines a public class named
MultipleFilterOperation.
3.Main Method (public
static void main(String[] args) { ... }):
·
This is the entry point of the program, where
execution begins.
4.List Initialization:
·
List<String>
name = Arrays.asList("Java", "C++", "C",
"Python", "Assembly", "PHP");
Creates a fixed-size list (name)
containing strings using Arrays.asList, which converts the provided elements
into a List<String>.
5.Stream Pipeline:
·
name.stream(): Converts
the List into a stream of strings (Stream<String>).
·
.filter(str
-> str.length() > 1 && str.length() < 4): Filters
the stream to keep only those strings (str) whose length is greater than 1 and
less than 4.
·
str.length()
> 1: Ensures the string has more than 1 character.
·
str.length()
< 4: Ensures the string has less than 4 characters.
·
.forEach(System.out::println): For each
element that passes the filter, prints it to the console using the method
reference System.out::println.
Execution
Flow:
• The name list
is converted into a stream.
• The filter
operation processes each element in the stream and retains only those strings
that satisfy the length condition (str.length() > 1 && str.length()
< 4).
• The forEach
operation then prints each filtered string to the console.
Output:
The output of this program will be:
These are the strings from the name list that have a length
greater than 1 and less than 4 characters.
Summary:
This Java program demonstrates the use of streams (Stream
API) for filtering a list of strings (name). It filters strings based on their
length and prints the filtered strings to the console. The example showcases
how to chain operations (filter and forEach) on a stream to achieve specific
filtering criteria and output results.
03.Example
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterOperationAvoidingNullValues {
public static void main(String[] args) {
// Create a list of strings including null values
List<String> words= Arrays.asList("JAVA","C++",null,"PHP",null,null,"Assembly",null,"c");
// Stream operations on the 'words' list
List<String> result=words.stream()
// Filter operation: Keep only non-null elements
.filter(w-> w!=null)
// Collect the filtered elements into a new list
.collect(Collectors.toList());
// Print the result list containing non-null elements
System.out.println(result);
}
}
Explanation:
1.Imports:
·
import java.util.Arrays;: Imports the Arrays utility class
for working with arrays and collections.
·
import java.util.List;: Imports the List interface from the
java.util package.
·
import java.util.stream.Collectors;: Imports Collectors class from
java.util.stream for collecting stream elements into a collection.
2.Class
Declaration:
·
public class FilterOperationAvoidingNullValues
{ ... }: Defines a
public class named FilterOperationAvoidingNullValues.
3.Main Method
(public static void main(String[] args)
{ ... }):
·
This
is the entry point of the program, where execution begins.
4.List
Initialization:
·
List<String> words =
Arrays.asList("JAVA", "C++", null, "PHP", null,
null, "Assembly", null, "c");
Creates a
fixed-size list (words) containing strings, including null values, using
Arrays.asList, which converts the provided elements into a List<String>.
5.Stream Pipeline:
·
words.stream(): Converts the List into a stream of
strings (Stream<String>).
·
.filter(w -> w != null): Filters the stream to keep only those
strings (w) that are not null.
·
.collect(Collectors.toList()): Collects the filtered elements into a
new list (List<String>). The Collectors.toList() method collects stream
elements into a List.
Output:
System.out.println(result);:
Prints the resulting list (result) containing non-null elements to the console.
Execution Flow:
·
The
words list is converted into a stream.
·
The
filter operation processes each element in the stream and retains only those
strings that are not null.
·
The
collect operation gathers the filtered elements into a new list (result).
Finally, the
result list is printed to the console.
Output:
The output of
this program will be:
These are the
non-null strings from the words list after filtering out the null values.
Summary:
This Java
program demonstrates the use of streams (Stream API) for filtering a list of
strings (words) to remove null values. It then collects the filtered strings
into a new list (result) using Collectors.toList() and prints the resulting
list. This example showcases how to handle and filter out null values
effectively using stream operations in Java.
04.Example
import java.util.ArrayList;
import java.util.List;
// Student class with fields id, name, and phoneNumber
class Student{
int id;
String name;
int phoneNumber;
// Constructor to initialize Student objects
public Student(int id,String name, int phoneNumber){
this.id=id;
this.name= name;
this.phoneNumber=phoneNumber;
}
}
public class FilterOperationVariousData {
public static void main(String[] args) {
// Create a list to hold Student objects
List <Student>studentList=new ArrayList<Student>();
// Adding Student objects to the list
studentList.add(new Student(001,"Amal",0112233445));
studentList.add(new Student(002,"Kamal",0112233455));
studentList.add(new Student(003,"Namal",0112233465));
studentList.add(new Student(004,"Chamal",0112233475));
studentList.add(new Student(005,"Rayan",011232334));
studentList.add(new Student(006,"Kevin",0112433451));
// Stream operations on the studentList
studentList.stream()
// Filter operation: Keep only students with id less than 004
.filter(p -> p.id<004)
// For each filtered student, print the name to the console
.forEach(idList -> System.out.println(idList.name));
}
}
Explanation:
01.Student Class (class
Student { ... }):
·
Defines a simple class Student with three
fields: id, name, and phoneNumber.
·
Provides a constructor public Student(int id,
String name, int phoneNumber) to initialize these fields when creating Student
objects.
02.Main Class (public
class FilterOperationVariousData { ... }):
·
Contains the main method, which serves as the
entry point of the program.
03.List Initialization:
·
List<Student>
studentList = new ArrayList<Student>();: Initializes an ArrayList
named studentList that holds Student objects.
04.Adding Students to the List:
studentList.add(new
Student(001, "Amal", 0112233445));
studentList.add(new
Student(002, "Kamal", 0112233455));
studentList.add(new
Student(003, "Namal", 0112233465));
studentList.add(new
Student(004, "Chamal", 0112233475));
studentList.add(new
Student(005, "Rayan", 011232334));
studentList.add(new
Student(006, "Kevin", 0112433451));
Adds instances of Student to the studentList using the add
method of ArrayList.
04.Stream Pipeline:
·
studentList.stream():
Converts the studentList into a stream of Student objects
(Stream<Student>).
·
.filter(p
-> p.id < 004): Filters the stream to keep only those students (p)
whose id is less than 004.
·
.forEach(student
-> System.out.println(student.name)): For each student that passes the
filter, prints the name of the student to the console using a lambda expression
(student -> System.out.println(student.name)).
Execution Flow:
·
The studentList is converted into a stream.
·
The filter operation processes each student in
the stream and retains only those with an id less than 004.
·
The forEach operation then prints each filtered
student's name to the console.
Output:
The output of this program will be:
These are the names of the students whose IDs are less than
004, as filtered by the stream operations.
Summary:
This Java program demonstrates the use of streams (Stream
API) to filter a list of Student objects (studentList). It filters students
based on their ID (id < 004) and prints the names of the filtered students
to the console. The example shows how to effectively use streams for filtering
and processing data from a collection of custom objects in Java.
Comments
Post a Comment