How Can I use Java Stream To Build a List

2019-02-27 19:45发布

问题:

Say I have two variables : a = 5, b = 8,

And I want :

Arrays.asList(5, 6, 7, 8)

How Can I Use Java stream To get this?

回答1:

you can use IntStream.rangeClosed to generate the numbers and collect into a list.

List<Integer> result = IntStream.rangeClosed(a, b)
                                .boxed()
                                .collect(Collectors.toList());