Passing a collection using a reduce (3 parameters) function - streams java 8

前端 未结 2 447
离开以前
离开以前 2021-01-05 17:25

I am trying to calculate the multiplication of a value using the previous two values using java 8\'s stream. I want to call a function that will return an array/list/collect

2条回答
  •  轮回少年
    2021-01-05 17:55

    Just for completeness, here is a solution which does not need an additional class.

    List output = Stream.iterate(
        (ToIntFunction)f -> f.applyAsInt(1, 2),
        prev -> f -> prev.applyAsInt((a, b) -> f.applyAsInt(b, a*b) )
    )
    .limit(9).map(pair -> pair.applyAsInt((a, b)->a))
    .collect(Collectors.toList());
    

    This is a functional approach which doesn’t need an intermediate value storage. However, since Java is not a functional programming language and doesn’t have optimizations for such a recursive function definition, this is not recommended for larger streams.

    Since for this example a larger stream would overflow numerically anyway and the calculation is cheap, this approach works. But for other use cases you will surely prefer a storage object when solving such a problem with plain Java (as in Stuart Marks’ answer)

提交回复
热议问题