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.

Answer

You can do it like this:

IntStream.range(0, numbers.length)
  .forEach(index -> {
    doubleNumbers[index] = numbers[index] * 2;
    tripleNumbers[index] = numbers[index] * 3;
  });

Leave a Reply

Your email address will not be published. Required fields are marked *