Introduction
Filtering a list is a common task in programming, essential for extracting specific data based on certain criteria. With the introduction of Streams in Java 8, filtering has become more expressive and concise, allowing developers to write clean and readable code. In this guide, we will explore how to filter a list using Java 8 Streams, covering different scenarios such as filtering based on conditions, filtering custom objects, and combining multiple conditions.
Problem Statement
The task is to create a Java program that:
- Accepts a list of elements.
- Filters the list based on given conditions.
- Outputs the filtered list.
Example 1:
- Input: List of integers
[5, 12, 8, 1, 19]
, filter numbers greater than 10. - Output:
[12, 19]
Example 2:
- Input: List of strings
["apple", "banana", "orange", "mango"]
, filter strings starting with "a". - Output:
["apple"]
Solution Steps
- Input List: Start with a list of elements that can either be hardcoded or provided by the user.
- Filter the List Using Streams: Use the
filter()
method to apply conditions and filter the list. - Display the Result: Print the filtered list.
Java Program
Filtering Numbers: Filter a List of Integers Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Filter a List of Integers Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class FilterListNumbers {
public static void main(String[] args) {
// Step 1: Take input list
List<Integer> numbers = Arrays.asList(5, 12, 8, 1, 19);
// Step 2: Filter the list using streams (numbers greater than 10)
List<Integer> filteredNumbers = numbers.stream()
.filter(n -> n > 10)
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Filtered List: " + filteredNumbers);
}
}
Filtering Strings: Filter a List of Strings Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Filter a List of Strings Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class FilterListStrings {
public static void main(String[] args) {
// Step 1: Take input list
List<String> fruits = Arrays.asList("apple", "banana", "orange", "mango");
// Step 2: Filter the list using streams (strings starting with 'a')
List<String> filteredFruits = fruits.stream()
.filter(fruit -> fruit.startsWith("a"))
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Filtered List: " + filteredFruits);
}
}
Filtering Custom Objects: Filter a List of Student Objects Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Filter a List of Student Objects Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class FilterListCustomObjects {
public static void main(String[] args) {
// Step 1: Take input list of custom objects
List<Student> students = Arrays.asList(
new Student("John", 25),
new Student("Alice", 30),
new Student("Bob", 22)
);
// Step 2: Filter the list using streams (age greater than 23)
List<Student> filteredStudents = students.stream()
.filter(student -> student.getAge() > 23)
.collect(Collectors.toList());
// Step 3: Display the result
filteredStudents.forEach(student ->
System.out.println(student.getName() + ": " + student.getAge())
);
}
}
// Custom class Student
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Explanation of the Programs
-
Filtering Numbers: The first program filters a list of integers, keeping only the numbers greater than 10. The
filter()
method is used to apply this condition, andcollect(Collectors.toList())
gathers the results into a new list. -
Filtering Strings: The second program filters a list of strings, keeping only those that start with the letter ‘a’. This demonstrates the use of the
filter()
method to apply string-specific conditions. -
Filtering Custom Objects: The third program filters a list of
Student
objects, keeping only those whose age is greater than 23. Thefilter()
method is used with a condition based on a property of theStudent
class, showing how to filter custom objects in a stream.
Output Example
For all methods, the output will be:
Example 1:
Input: [5, 12, 8, 1, 19]
Output: Filtered List: [12, 19]
Example 2:
Input: ["apple", "banana", "orange", "mango"]
Output: Filtered List: [apple]
Example 3:
Input: [Student("John", 25), Student("Alice", 30), Student("Bob", 22)]
Output:
John: 25
Alice: 30
Advanced Considerations
-
Combining Multiple Conditions: You can combine multiple conditions in the
filter()
method using logical operators like&&
and||
. For example, you might filter students by age and name simultaneously. -
Performance Considerations: Filtering using Streams is efficient and suitable for typical list sizes. The method is more concise and readable compared to traditional loops, making it a preferred choice in modern Java applications.
-
Null Handling: Streams handle null values gracefully. However, if the list or elements might be null, you should add null checks to avoid
NullPointerException
.
Conclusion
This guide provides multiple methods for filtering a list using Java 8 Streams, covering filtering numbers, strings, and custom objects like Student
. Java 8 Streams offer a powerful and concise way to filter lists, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the filtering techniques demonstrated in this guide.