Decided to get a little JDK 8 practice in today, so I built two methods to print out the golden ratio, one uses the Stream API the other does not. Wanted to request general feedback on how well I implemented these methods (mainly the stream generator,) considering the given task and if there is anything I could have done better.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created on 7/5/2016.
*
*/
public class Fibonacci {
public static void main(String[] args) {
System.out.printf("Fibonacci Old: %s%n", String.join(", " , Fibonacci.calculateFib(10).stream()
.map(Object::toString)
.collect(Collectors.toList())));
System.out.printf("Fibonacci New: %s%n", String.join(", " , Fibonacci.generateFib()
.limit(10)
.map(Object::toString)
.collect(Collectors.toList())));
}
private static List<Integer> calculateFib(int fibCount){
List<Integer> fibSequence = new ArrayList<>();
fibSequence.add(0);
fibSequence.add(1);
for(int i = 2; i < fibCount; i++){
fibSequence.add(fibSequence.get(i-1) + fibSequence.get(i-2));
}
return fibSequence;
}
private static Stream<Integer> generateFib() {
return Stream.generate(new Supplier<Integer>() {
List<Integer> list = new ArrayList<>(Arrays.asList(0, 1));
int i = 0;
@Override
public Integer get() {
list.add(list.get(i) + list.get(i+1));
return list.get(i++);
}
});
}
}