Preface
filter()
is an intermediate operation in the Java Stream API that is used to filter elements in a stream based on a given condition. It receives aPredicate
(Assertion, that is, returnboolean
function) as a parameter, filter out elements that meet the conditions and collect them into a new stream.
1. Basic usage
filter()
Allows you to filter elements in a stream based on certain conditions. For example, if you have an integer stream and want to keep only even numbers in it, you can usefilter()
To achieve:
List<Integer> numbers = (1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = () .filter(n -> n % 2 == 0) // Keep even numbers .collect(()); // Terminal operation, collect the results as List (evenNumbers); // Output: [2, 4, 6]
In this example:
-
filter(n -> n % 2 == 0)
: is a filter condition used to retain those numbers that can be divisible by 2, i.e. even numbers. -
filter()
Each element in the stream will be traversed and checked using this condition. Elements that meet the conditions will continue to remain in the stream, and elements that do not meet the conditions will be discarded.
2. Predicate function
filter()
The parameter is aPredicate
Interface, this interface has only one abstract methodboolean test(T t)
, it receives an input and returns aboolean
Value. thisPredicate
Used to define filter criteria.
Example: Filter numbers greater than 3
List<Integer> numbers = (1, 2, 3, 4, 5); List<Integer> greaterThanThree = () .filter(n -> n > 3) // Keep numbers greater than 3 .collect(()); (greaterThanThree); // Output: [4, 5]
In this example,n -> n > 3
It's aPredicate
, which means filtering out numbers greater than 3.filter()
Method according to thisPredicate
to retain elements that meet the conditions.
3. Chain call filter()
You can call it multiple timesfilter()
, to apply multiple conditions to elements in the stream. for example:
List<Integer> numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> filteredNumbers = () .filter(n -> n > 3) // The first condition: greater than 3 .filter(n -> n < 8) // The second condition: less than 8 .collect(()); (filteredNumbers); // Output: [4, 5, 6, 7]
here,filter()
Called twice:
- The first one
filter(n -> n > 3)
: Filter out numbers greater than 3. - The second one
filter(n -> n < 8)
: Filter out numbers less than 8 among the remaining numbers.
The final result is the element that meets these two conditions at the same time.[4, 5, 6, 7]
。
4. Air flow
filter()
After the operation, the stream may become an empty stream. If no elements satisfyfilter()
The flow will become an empty stream, but no exception will be thrown. In this case, subsequent intermediate operations can still be applied to the empty stream, but there are no elements to handle:
List<Integer> numbers = (1, 2, 3); List<Integer> result = () .filter(n -> n > 10) // No element meets the condition .collect(()); (result); // Output: []
In this example,filter(n -> n > 10)
Filter out elements greater than 10, but no elements in the stream meet this condition, so the final return is an empty list.[]
。
5. Lazy evaluation of filter()
filter()
It is a lazy operation, that is,Intermediate operation. It itself does not execute immediately, but waits for the terminal operation on the stream (such ascollect()
、forEach()
) will be executed only when it is called.
For example:
Stream<Integer> stream = (1, 2, 3, 4) .filter(n -> { ("Filtering: " + n); return n % 2 == 0; }); ("Before terminal operation"); // Terminal operation, trigger filter executionList<Integer> evenNumbers = (()); ("After terminal operation: " + evenNumbers);
The output result is:
Before terminal operation
Filtering: 1
Filtering: 2
Filtering: 3
Filtering: 4
After terminal operation: [2, 4]
You can see that when calling terminal operationscollect()
Before,filter()
Not executed; only when the terminal operation is called,filter()
It’s only when I really start filtering elements.
6. Use in combination with other stream operations
filter()
Often used in combination with other stream operations, such asmap()
、sorted()
wait.
Example: Used in combination with filter()
List<String> words = ("apple", "banana", "cherry", "date"); List<String> result = () .filter(word -> () > 5) // Filter words with lengths greater than 5 .map(String::toUpperCase) // Convert a word that meets the criteria to capitalize .collect(()); (result); // Output: [BANANA, CHERRY]
In this example:
-
filter(word -> () > 5)
: Filter out words with lengths greater than 5. -
map(String::toUpperCase)
: Convert the remaining words to capitalization. -
collect(())
: Collect the stream results into oneList
。
7. Combine multiple Predicate conditions
Sometimes you may need to apply multiple conditions to elements in the stream. You can passPredicate
ofand()
、or()
、negate()
etc.com combination of multiple conditions.
Example: Filter out numbers greater than 2 and even
List<Integer> numbers = (1, 2, 3, 4, 5, 6); List<Integer> result = () .filter(n -> n > 2 && n % 2 == 0) // Combination conditions: greater than 2 and even .collect(()); (result); // Output: [4, 6]
You can also usePredicate
Combination method:
Predicate<Integer> greaterThanTwo = n -> n > 2; Predicate<Integer> isEven = n -> n % 2 == 0; List<Integer> result = () .filter((isEven)) // Use Predicate's and() method .collect(()); (result); // Output: [4, 6]
This method can enhance the readability and reusability of the code.
8. Use filter() in object collection
filter()
It can not only be used for simple types of streams (such asInteger
、String
), can also be used for streams of complex objects. For example, in a containingPerson
Filter people older than 18 in the object list:
class Person { String name; int age; Person(String name, int age) { = name; = age; } @Override public String toString() { return name + " (" + age + ")"; } } List<Person> people = ( new Person("Alice", 22), new Person("Bob", 17), new Person("Charlie", 20) ); List<Person> adults = () .filter(person -> > 18) // Screen people older than 18 .collect(()); (adults); // Output: [Alice (22), Charlie (20)]
Summarize:
-
filter()
is an intermediate operation for the givenPredicate
Filter elements in the stream and retain elements that meet the conditions. - It does not change the type of element, it only determines which elements can continue to be passed to the next stream operation.
- because
filter()
is lazy evaluation, and intermediate operations will only be executed when the terminal operation is called. -
filter()
Suitable for filtering of various complex objects, and can be used withmap()
Use other stream operations in combination.
This is the end of this article about the usage of filter() in Java Stream stream. For more related content on filter() in Java Stream stream, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!