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.
Remember that loops use an imperative style and Streams a declarative style, so Streams are likely to be much easier to maintain. If you have a small list, loops perform better. If you have a huge list, a parallel stream will perform better.
Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.
Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse.
You can do it like this:
IntStream.range(0, numbers.length)
.forEach(index -> {
doubleNumbers[index] = numbers[index] * 2;
tripleNumbers[index] = numbers[index] * 3;
});
You can apply the doubling and tripling within the stream:
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.println("Double Numbers");
Arrays.stream(numbers).map(x -> x * 2).forEach(System.out::println);
System.out.println("Triple Numbers");
Arrays.stream(numbers).map(x -> x * 3).forEach(System.out::println);
}
though technically that's still iterating over the array twice.
As a trick you could instead collect the results in a Map
:
Map<Integer, Integer> m = Arrays.stream(numbers)
.boxed()
.collect(Collectors.toMap(
x -> x * 2,
x -> x * 3
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With