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
  • 3,182
  • 7
  • 28
  • 38
Łukasz
  • 1,980
  • 6
  • 32
  • 52

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
  • 321,522
  • 82
  • 660
  • 783
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
  • 8,122
  • 19
  • 71
  • 128