Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Streams instead of for loop in java 8

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.

like image 676
Sarang Shinde Avatar asked Jan 15 '17 13:01

Sarang Shinde


People also ask

Is Java stream better than for loop?

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.

Is Java 8 stream faster than for loop?

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.

Which is faster stream or for loop in Java?

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.


2 Answers

You can do it like this:

IntStream.range(0, numbers.length)
  .forEach(index -> {
    doubleNumbers[index] = numbers[index] * 2;
    tripleNumbers[index] = numbers[index] * 3;
  });
like image 131
thegauravmahawar Avatar answered Oct 08 '22 06:10

thegauravmahawar


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
        ));
like image 30
jon-hanson Avatar answered Oct 08 '22 04:10

jon-hanson