Ask Your Question
2

How can a list of odd and even numbers be obtained using a Stream?

asked 2023-07-18 03:52:16 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-18 04:08:01 +0000

david gravatar image

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]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 03:52:16 +0000

Seen: 11 times

Last updated: Jul 18 '23