In this post, we will see CollectionUtils filter() example in Java. we will see how to use CollectionUtils filter()
method.
The filter()
method in the CollectionUtils
class in Java is used to filter a collection by applying a specified predicate (a condition that evaluates to true or false) to each element in the collection.
Suppose we have a list of integers, and you want to filter out all the even numbers from the list. Here’s let’s see an example that show how we can use the filter()
method from the CollectionUtils
class:
CollectionUtils filter() Example in Java
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class FilterExample {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
// Use CollectionUtils.filter() to filter out even numbers
CollectionUtils.filter(numbers, n -> n % 2 != 0);
// Print the filtered list
System.out.println(numbers);
}
}
Suppose you have a list of integers, and you want to filter out all the even numbers from the list. Here’s how you can use the filter()
method from the CollectionUtils
class.
Note – We need to add the below dependency in maven to use org.apache.commons.lang3.CollectionUtils filter()
method. We can download the apache-commons maven dependency from here.
pom.xml changes
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
In the above example, we import the org.apache.commons.collections4.CollectionUtils
class and create a list of integers. We then call the filter()
method from the CollectionUtils
class and pass in the list of integers and a lambda expression n -> n % 2 != 0
as arguments. The lambda expression is a predicate that evaluates to true for all odd numbers and false for all even numbers.
The filter()
method modifies the original list in place and removes all the even numbers from the list. Finally, we print the filtered list to the console. The output should be [1, 3, 5]
.
That’s all about CollectionUtils filter() Example in Java.
See docs.
Related post.
- CollectionUtils isEmpty() Example in Java.
- StringUtils isEmpty() and isBlank () Example in Java.
- StringUtils join() Example in Java.
- CollectionUtils union() Example in Java
- CollectionUtils intersection() Example in Java
- CollectionUtils isEqualCollection() Example in Java
- StringUtils isAlpha() example in Java
- StringUtils isNumeric() example in Java