0

Have this:

    List<Integer> list = new LinkedList<>();

    for (int i = 0; i < upperBound; i += step) {
        list.add(i);
    }

How can I replace it with functional styled streams?

thanks

Stefan Zobel
  • 2,847
  • 7
  • 25
  • 34
Łukasz
  • 1,668
  • 5
  • 25
  • 45

2 Answers2

2

Your loop looks fine.

If you absolutely want to use a stream, you can create an IntStream and box it into a List. For example:

int elementCount = upperBound / step;
if (upperBound % step != 0) elementCount++;

List<Integer> list = IntStream.range(0, elementCount)
         .map(i -> i * step)
         .boxed()
         .collect(toCollection(LinkedList::new));

Note that defining the upper bound is not straightforward.

assylias
  • 310,138
  • 72
  • 642
  • 762
1

You can use the range function in IntStream :

List<Integer> collect = IntStream.range(startRange, upperBound).filter(x -> (x % step) == 0).boxed().collect(toCollection(LinkedList::new));

You can find more information in this answer

Dimitri
  • 7,858
  • 18
  • 72
  • 124