Home > Software design >  Make a stream to generate the multiples of three
Make a stream to generate the multiples of three

Time:12-01

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

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

CodePudding user response:

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

  • Related