Fibonacci Sequence by Modern Java

Fibonacci sequence is one of the well known wonders in mathematics and sciences.  The sequence that captures a type of essence of the universe has always been intriguing.  Below is the code for generating the sequence that the algorithm can be written in an elegant way by modern Java.

class Tuple<T, U> { 
    public final T _1; 
    public final U _2; 
    public Tuple(T t, U u) { 
      this._1 = t; 
      this._2 = u; 
    } 
}

class Fibonnaci {  

    public static void main(String[] args) { 

        Function<Integer, Stream<Integer>> getFiboStream = (n) -> {
            Tuple<Integer, Integer> seed = new Tuple<>(1, 1);
            UnaryOperator<Tuple<Integer, Integer>> f = (x) -> new Tuple<>(x._2, x._1 + x._2);  
            return Stream.iterate(seed, f)
                         .map(x -> x._1)
                         .limit(n);
        };

        String result = getFiboStream.apply(20)
                                     .map(x -> x.toString())
                                     .collect(Collectors.joining(", "));                                    
        System.out.println(result);
        
    }
}

Output:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765

Notice that the getFiboStream function is a Pure Function in that:
  • The function brings no side-effects
  • The return value depends only on the input parameter that passed to the function
By returning a Stream object, the methods of Stream become available for manipulating the numbers.  For generating a very long sequence of Fibonacci numbers, consider using Long or BigInteger instead of Integer.

Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream