int [] numbers = {1,2,3,4,5,6,7,8};
int [] doubleNumbers = new int[numbers.length];
int [] tripleNumbers = new int[numbers.length];
for(int index = 0; index < numbers.length; index++)
{
doubleNumbers[index] = numbers[index] * 2;
tripleNumbers[index] = numbers[index] * 3;
}
System.out.println("Double Numbers");
Arrays.stream(doubleNumbers).forEach(System.out::println);
System.out.println("Triple Numbers");
Arrays.stream(tripleNumbers).forEach(System.out::println);
I have above code where I have used for loop and double and triple the numbers and stored it in different arrays in single loop. Can anybody help me to write the same code using streams with its map and other methods without iterating numbers array twice.
Seems like your question is more complicated than just using Java Stream API. The better way is define some wrapper class like Num.class:
Then you can just wrap your array elements into this object and call
powerOf
method where you need. With your implementation you are creating unnecessary arrays for keeping powered values. And using Stream API in this case is more convinient:You can do it like this:
You can use
stream
withforEach
method to populatecollections
of doubles and triples e.g.:Another example with
map
andcollect
:You can apply the doubling and tripling within the stream:
though technically that's still iterating over the array twice.
As a trick you could instead collect the results in a Map: