Create a Stream of Integers
Let's create a Stream of Integers and filter out the even numbers from it. We will declare a list of integers, convert it into a Stream, and then use the filter()
method to filter out the even numbers.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamFilter {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> stream = numbers.stream();
Stream<Integer> evenNumbers = stream.filter(i -> i % 2 == 0);
List<Integer> result = evenNumbers.collect(Collectors.toList());
System.out.println(result); // Output: [2, 4, 6, 8, 10]
}
}
In the above code, we declare a list of integers, convert it into a Stream using the stream()
method, and then filter out the even numbers using the filter()
method.