如何使用 Java Streams 获取 1 到 100 的斐波那契数列并将其添加到地图中
How to fetch fibonacci series of 1 to 100 using Java Streams and add it into a map
我可以使用普通方法编写此代码。但是使用 Streams 我试过这样但是限制在这里对那个范围不起作用并且 IntStream.range() 方法我不能在这里使用。
Stream.iterate(new int[]{0,1}, f -> new int[]{f[1], f[0]+f[1]})
.limit(10)
.map(n -> n[0])
.forEach(System.out::println);
//.collect(Collectors.toList());
请回复。
您可以使用任何高于 8 的 Java 版本,然后是 takeWhile
和 dropWhile
:
import java.util.stream.Stream;
public class Temp {
public static void main(String [] args){
Stream
//Generate a stream of arrays like this {0,1}, {1, 1}, {1, 2}, {2, 3}, {3, 5}...etc.
.iterate(new int[] { 0, 1 }, f -> new int[] { f[1], f[0] + f[1] })
//Keep only the 1st element of each array.
.map(n -> n[0])
//Drop only 0.
.dropWhile(i -> i < 1)
//Take any number which is <= 100.
.takeWhile(i -> i <= 100)
.forEach(System.out::println);
}
}
当然可以用{ 1, 2 }
作为seed来避免dropWhile
Java 8 不提供 limiting/stopping 流的基于谓词的方式,因此我会坚持使用该版本的循环。
我可以使用普通方法编写此代码。但是使用 Streams 我试过这样但是限制在这里对那个范围不起作用并且 IntStream.range() 方法我不能在这里使用。
Stream.iterate(new int[]{0,1}, f -> new int[]{f[1], f[0]+f[1]})
.limit(10)
.map(n -> n[0])
.forEach(System.out::println);
//.collect(Collectors.toList());
请回复。
您可以使用任何高于 8 的 Java 版本,然后是 takeWhile
和 dropWhile
:
import java.util.stream.Stream;
public class Temp {
public static void main(String [] args){
Stream
//Generate a stream of arrays like this {0,1}, {1, 1}, {1, 2}, {2, 3}, {3, 5}...etc.
.iterate(new int[] { 0, 1 }, f -> new int[] { f[1], f[0] + f[1] })
//Keep only the 1st element of each array.
.map(n -> n[0])
//Drop only 0.
.dropWhile(i -> i < 1)
//Take any number which is <= 100.
.takeWhile(i -> i <= 100)
.forEach(System.out::println);
}
}
当然可以用{ 1, 2 }
作为seed来避免dropWhile
Java 8 不提供 limiting/stopping 流的基于谓词的方式,因此我会坚持使用该版本的循环。