I have the following code all over my project and I would like to know if it is possible to write the same in less lines of code by replacing it with a single for loop that increments or decrements depending on whether endPosition is bigger or smaller than startPosition. Is that possible?
if (endPosition > startPosition) {
    for (int i = startPosition; i <= endPosition; i++) {
        doStuff(i);
    }
} else {
    for (int i = startPosition; i >= endPosition; i--) {
        doStuff(i);
    }
}
Edit1: I have changed the words 'optimize' to 'write in less lines of code'. Also, I added the index i as a parameter of doStuff, to emphasize that it's important. The order in which each element is visited, however, is not.
 
     
     
     
     
     
     
     
     
    