1 | initial version |
To get a list of odd and even numbers using a stream, you can start with a range of numbers and filter them based on their parity (even/odd).
Here's an example code snippet in Java:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<Integer> oddNumbers = IntStream.rangeClosed(1, 10)
.filter(n -> n % 2 != 0)
.boxed()
.collect(Collectors.toList());
List<Integer> evenNumbers = IntStream.rangeClosed(1, 10)
.filter(n -> n % 2 == 0)
.boxed()
.collect(Collectors.toList());
System.out.println("Odd numbers: " + oddNumbers);
System.out.println("Even numbers: " + evenNumbers);
}
}
In this example, we first call the rangeClosed
method on IntStream
to generate a range of numbers from 1 to 10 (inclusive). We then use the filter
method to selectively keep only odd or even numbers, based on the condition n % 2 != 0
for odd numbers, and n % 2 == 0
for even numbers.
Finally, we box the int
values into Integer
objects using the boxed
method so that we can collect them into a List
using the collect
method with the Collectors.toList()
collector.
The output of the above code will be:
Odd numbers: [1, 3, 5, 7, 9]
Even numbers: [2, 4, 6, 8, 10]