简体   繁体   English

制作一个 stream 生成三的倍数

[英]Make a stream to generate the multiples of three

I'm trying to generate a stream of integers, so i make a static method that return a Stream我正在尝试生成整数的 stream,所以我创建了一个返回 Stream 的 static 方法

Here you can found the method:在这里你可以找到方法:

public static Stream<Integer> multipleOf3(){
    return Stream.iterate(1, x -> 3*x).limit(10);
}

However this method don't return me the mutitple of three but the power of three然而,这种方法不会返回我三的倍数,而是三的幂

i call the method like that:我这样称呼方法:

multipleDe3().forEach(System.out::println);

and i have this result:我有这个结果:

1
3
9
27
81
243
729
2187
6561
19683

I think the iterate function use the previous result, the seeds = 1, so x = 1 and then:我认为迭代 function 使用前面的结果,种子 = 1,所以 x = 1,然后:

3*1 = 3, 
3*3 = 9, 
3*9 = 27, etc... 

So if anyone has an idea to calculate the multiple without use the previous result tell me please因此,如果有人想在不使用先前结果的情况下计算倍数,请告诉我

public static Stream<Integer> multipleOf3(){
    return Stream.iterate(0, x -> 3+x).skip(1).limit(10);
}

public static void main(String[] args) {
    multipleOf3().forEach(System.out::println);
}

Output: 3 6 9 12 15 18 21 24 27 30 Output:3 6 9 12 15 18 21 24 27 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM