In Java, Stream
is a feature introduced in Java 8 to provide a functional programming style to process collections of data. It allows you to perform aggregate functions on collections, such as filtering, mapping, sorting, and reducing.
Filter
is one of the intermediate operations in the Stream
API. It is used to select elements from a Stream
based on a specified condition. The filter
method takes a predicate, which is a functional interface that takes an element of the stream as input and returns a boolean value. If the returned value is true
, the element is included in the new stream, otherwise it is skipped.
Here’s an example of how to use filter
to select even numbers from a list of integers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
In the above code, we created a list of integers and used the stream()
method to create a stream of integers. We then applied the filter
method to this stream, which selects only the elements that are even. Finally, we collected the filtered elements into a new list using the collect
method.
Java Stream filter() example:
Sure, here’s an example of how to use the filter()
method in Java:
import java.util.Arrays; import java.util.List; public class StreamFilterExample { public static void main(String[] args) { List<String> fruits = Arrays.asList("apple", "banana", "orange", "kiwi", "pear"); // Filter the fruits that start with the letter 'a' List<String> filteredFruits = fruits.stream() .filter(fruit -> fruit.startsWith("a")) .collect(Collectors.toList()); // Print the filtered fruits System.out.println(filteredFruits); // Output: [apple] } }
In the above example, we created a list of fruits using the Arrays.asList()
method. We then created a stream of fruits using the stream()
method. We applied the filter()
method on this stream, which takes a predicate (in this case, a lambda expression fruit -> fruit.startsWith("a")
) that returns true
for elements that start with the letter “a”. Finally, we collected the filtered fruits into a new list using the collect()
method.
The output of the above code will be [apple]
, since only the fruit “apple” starts with the letter “a”.