In Java 8, the Stream API provides an efficient and functional way to process collections of data. You can create a stream from a collection and perform various operations like filtering, mapping, reducing, etc.
Here’s how you can create a stream from a collection and perform a filter operation:
Steps to Create a Stream and Perform Filter Operation:
- Create a Stream from a Collection:
- You can create a stream from any collection (e.g.,
List,Set, etc.) by calling the.stream()method. - Use the
filter()Method: - The
filter()method takes a predicate (a functional interface that returns a boolean) as an argument and returns a new stream that contains only the elements that match the predicate. - Perform Terminal Operation:
- After filtering, you usually perform a terminal operation (like
collect(),forEach(), etc.) to consume the stream and get the result.
Example:
Let’s say we have a list of integers and we want to filter out only the even numbers.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamFilterExample {public static void main(String args) {
// Step 1: Create a list of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Step 2: Create a stream from the list and filter even numbers
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0) // Filter out even numbers
.collect(Collectors.toList()); // Collect result back to a list
// Step 3: Print the filtered list
System.out.println("Even numbers: " + evenNumbers);
}
}
Explanation:
numbers.stream(): Creates a stream from the listnumbers.filter(n -> n % 2 == 0): Filters out elements where the condition (n is even) is true.collect(Collectors.toList()): Collects the filtered elements into a new list.
Output:
Even numbers: [2, 4, 6, 8, 10]
More Examples of Filter Operations:
Filtering Strings Based on Length:
Filter a list of strings to include only strings with a length greater than 3.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StringFilterExample {public static void main(String args) {
List<String> names = Arrays.asList("John", "Paul", "Mike", "Sam", "Anna");
// Filter names with length > 3
List<String> filteredNames = names.stream()
.filter(name -> name.length() > 3)
.collect(Collectors.toList());
System.out.println("Filtered names: " + filteredNames);
}
}
Output:
Filtered names: [John, Paul, Mike]
How the Filter Operation Works:
- The
filter()method takes a predicate as a parameter. The predicate is a functional interface that evaluates the condition on each element of the stream. - If the predicate returns
truefor an element, that element is included in the resulting stream. - If it returns
false, the element is excluded from the result.
Summary:
- Stream Creation: Use
.stream()on a collection to create a stream. - Filter Operation: Use
.filter()to apply a condition to elements and keep only the matching ones. - Terminal Operation: Use methods like
collect(),forEach(), orreduce()to consume the stream after filtering.
The Stream API is powerful and provides an easy, declarative way to handle collections in Java, improving both the readability and efficiency of your code.