Minimamut
Minimamut

Reputation: 87

java 8 make a stream of the multiples of two

I'm practicing streams in java 8 and im trying to make a Stream<Integer> containing the multiples of 2. There are several tasks in one main class so I won't link the whole block but what i got so far is this:

Integer twoToTheZeroth = 1;
UnaryOperator<Integer> doubler = (Integer x) -> 2 * x;
Stream<Integer> result = ?;

My question here probably isn't related strongly to the streams, more like the syntax, that how should I use the doubler to get the result?

Thanks in advance!

Upvotes: 3

Views: 2635

Answers (2)

daniu
daniu

Reputation: 14999

You can use Stream.iterate.

Stream<Integer> result = Stream.iterate(twoToTheZeroth, doubler);

or using the lambda directly

Stream.iterate(1, x -> 2*x);

The first argument is the "seed" (ie first element of the stream), the operator gets applied consecutively with every element access.

EDIT:

As Vinay points out, this will result in the stream being filled with 0s eventually (this is due to int overflow). To prevent that, maybe use BigInteger:

Stream.iterate(BigInteger.ONE, 
               x -> x.multiply(BigInteger.valueOf(2)))
      .forEach(System.out::println);

Upvotes: 10

shahaf
shahaf

Reputation: 4973

Arrays.asList(1,2,3,4,5).stream().map(x -> x * x).forEach(x -> System.out.println(x));

so you can use the doubler in the map caller

Upvotes: 1

Related Questions