Guava Sets.filter() method in Java
In this post, we will explain what the Guava Sets.filter() method does, how to use it, and what benefits it offers over other solutions.
Sometimes, you might want to filter a set of elements based on some criteria, such as a property, a condition, or a pattern. For example, you might want to select only the names that start with a certain letter, or the numbers that are divisible by a certain factor, or the strings that match a certain regular expression. Guava library provides is a way to deal with this problem: using the Guava Sets.filter() method.
1. Overview of Sets.filter() method
The Guava Sets.filter() method is a static method that takes two parameters: a set of elements and a predicate. The method returns a new set that contains only the elements of the original set that satisfy the predicate. The signature of the method is as follows:
|
1 |
public static <E> Set<E> filter(Set<E> unfiltered, Predicate<? super E> predicate) |
The first parameter is a Set<E> that represents the source set of elements. The second parameter is a Predicate<? super E> that represents the filtering criterion. The Predicate interface is a functional interface that takes an argument and returns a boolean value. In this case, the argument is an element of type E (or any supertype of E), and the result is true if the element matches the criterion, or false otherwise.
The return type of the method is a Set<E> that represents the filtered set of elements. The method has some constraints and properties:
- The source set must not contain
nullelements. If the source set containsnullelements, aNullPointerExceptionwill be thrown. - The predicate must not be null. If the predicate is
null, aNullPointerExceptionwill be thrown. - The filtered set is a live view of the original set. Any changes made to the filtered set affect the original set and vice versa.
- The filtered set is constrained by the predicate. If an element that does not satisfy the predicate is added to the filtered set, an
IllegalArgumentExceptionwill be thrown. - The order of the elements in the filtered set is not guaranteed. The order may vary depending on the implementation details and the iteration order of the source set.
- The filtered set may or may not support removal operations. This depends on whether the source set supports removal operations or not.
2. Usage of Sets.filter() method
To use the Guava Sets.filter() method, you need create a Predicate instance using any implementation you prefer, such as an anonymous class, a lambda expression, or a method reference. You can also use the predicates provided by the Predicates class, such as alwaysTrue(), alwaysFalse(), equalTo(), containsPattern(), etc. You can call the Sets.filter() method on your Set and Predicate instances and pass them as arguments. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import com.google.common.collect.Sets; import java.util.Set; class Main { public static void main(String[] args) { // Create a HashSet with four elements Set<String> names = Sets.newHashSet("John", "Jane", "Adam", "Tom"); // Create a filtered set with names that have four characters Set<String> result = Sets.filter(names, input -> input.length() == 4); System.out.println(result); // [John, Adam, Jane] } } |
Note that the Sets.filter() method does not create a copy of the original set, but rather a view of it. This means that adding or removing elements from the SetView will affect the original set as well. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import com.google.common.collect.Sets; import java.util.Set; class Main { public static void main(String[] args) { Set<Integer> numbers = Sets.newHashSet(1, 2, 3, 4, 5); Set<Integer> evens = Sets.filter(numbers, input -> input % 2 == 0); evens.add(6); // this is allowed // [1, 2, 3, 4, 5, 6] System.out.println(numbers); } } |
3. Benefits of using Sets.filter() method
There are several benefits of using Guava Sets.filter() method over other solutions for filtering a set of elements:
- It is concise and expressive. You don’t need to write loops or streams to filter a set. You can simply call one method and pass a predicate as an argument.
- It is consistent and compatible. You can use it with any set of elements, regardless of the implementation or the type of the elements. You can also use it with any predicate, whether it is a custom one or a predefined one.
- It is lazy and efficient. You don’t need to create a new set in memory to store the filtered elements. The filtered set is a live view of the original set, which saves memory and time. The predicate is applied only when the filtered set is accessed, not when the method is called.
4. Conclusion
In this post, we have learned how to use Guava Sets.filter() method in Java. We have seen what the method does, how to use it, and what benefits it offers over other solutions. We have also provided some examples and code snippets to demonstrate its usage in different scenarios.
If you are interested in learning more about this method, you can check out the Guava official website or its GitHub repository.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)