Filtering Collections with Streams
Filtering is one of the most common operations performed on collections using the Java Stream API. Filtering allows you to select a subset of elements from a collection based on a given predicate.
Applying Filters
The filter()
method is used to apply a filter to a stream. This method takes a lambda expression or a method reference as an argument, which represents the filtering condition.
List<String> names = Arrays.asList("John", "Jane", "Bob", "Alice");
Stream<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"));
filteredNames.forEach(System.out::println);
In the example above, we create a stream from a list of names and then use the filter()
method to select only the names that start with the letter "J".
Chaining Multiple Filters
You can chain multiple filter()
calls to apply multiple filtering conditions to a stream.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> filteredNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.filter(n -> n > 5);
filteredNumbers.forEach(System.out::println);
In this example, we first filter the numbers to select only the even numbers, and then we apply a second filter to select only the even numbers greater than 5.
Combining Filters with Other Operations
Filtering can be combined with other stream operations, such as mapping, sorting, and reducing, to create more complex data transformations.
List<Person> persons = Arrays.asList(
new Person("John", 30),
new Person("Jane", 25),
new Person("Bob", 35),
new Person("Alice", 28)
);
List<String> youngAdultNames = persons.stream()
.filter(p -> p.getAge() >= 18 && p.getAge() < 30)
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(youngAdultNames);
In this example, we first filter the list of Person
objects to select only the young adults (between 18 and 30 years old), then we map the Name
property of each Person
object, and finally we collect the results into a new list.
By understanding the power of filtering with the Java Stream API, you can effectively manipulate and process your collections of data. In the next section, we'll explore more practical examples of applying filters.