Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading