Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change old for loop to IntStream?

this for loop iterate over an int array. it changes the value of (index-1) to the value of the current index. so the result should be, all the elements must equal the value of the last element.

int arr[] = {8, 5, 15, 23, 1, 7};
for (int i = arr.length - 1; i > 0; i--) {
    arr[i - 1] = arr[i];
}

how to change this old for loop to IntStream in Java 8, to make it modern.

like image 509
Pakbert Avatar asked Mar 07 '23 17:03

Pakbert


1 Answers

You could write like this using IntStream, but it's hardly any better:

IntStream.range(0, arr.length - 1).forEach(i -> arr[i] = arr[arr.length - 1]);

Note that I simplified the assignment, from arr[i - 1] = arr[i] to assigning to the value of the last element directly with arr[i] = arr[arr.length - 1]. If you wanted to write exactly the same assignment as in the original, it's possible, by mapping the range to reverse indexes, but that would be really much harder to read than the original.

If arr is guaranteed to be non-empty, then using Arrays.fill would be shorter and simpler:

Arrays.fill(arr, arr[arr.length - 1]);

All in all, I don't think you should worry too much about writing everything using streams. Use streams where they come naturally and easily. "Clever" code is not better code.

like image 163
janos Avatar answered Mar 10 '23 11:03

janos