How do I change the old for loop to intstream?
This for loop traverses the int array It changes the value of (index - 1) to the value of the current index So the result should be that all elements must be equal to 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 modernize the old for loop by changing it to intstream in Java 8
Solution
You can use intstream to write this, but it's almost no better:
IntStream.range(0,arr.length - 1).forEach(i -> arr[i] = arr[arr.length - 1]);
Note that I have simplified the assignment by directly assigning arr [i] = arr [i] to the value of the last element from arr [I – 1] = arr [arr.length – 1] If you want to write exactly the same assignment as the original version, you can do it by mapping the range to the reverse index, but it is more difficult to read than the original version
If arr is guaranteed to be non empty, use arrays Fill will be shorter and simpler:
Arrays.fill(arr,arr[arr.length - 1]);
In a word, I don't think you should worry too much about using streaming to write everything Use streams in natural and relaxed places "Smart" code is not better code