Java 8 Lambda expressions for solving fibonacci (non recursive way)

后端 未结 6 1142
广开言路
广开言路 2020-12-03 07:27

I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc.

H

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 07:58

    I know its a old question, but I feel worth to put some more ways to acheive using Pair<> and I came up with 2 ways to achieve using Stream API.

    //calculate Fibonacci at given place
    public static long fibonacciAt(int place) {
        Pair seed = new Pair<>(0, 1);
        //return Stream.iterate(seed, feed -> new Pair<>(feed.getValue(), feed.getValue() + feed.getKey())).limit(place).reduce((integerIntegerPair, integerIntegerPair2) -> integerIntegerPair2).orElse(seed).getValue();
        return Stream.iterate(seed, feed -> new Pair<>(feed.getValue(), feed.getValue() + feed.getKey())).limit(place).skip(place-1).findFirst().orElse(seed).getValue();
    }
    

    The commented return statement is also works fine which is using reduce.

    The later return statement is by skipping the number of pairs up to the place variable.(This is because we don't have findLast() method).

提交回复
热议问题