问题
I'm just refactoring some of my old projects to use features of Java 8.
int counter = 1;
for (Checker checker : checkers) {
if (counter < checkers.size()) {
checker.setNextChecker(checkers.get(counter++));
}
}
Here's kinda Chain of Resp pattern. And I need to set next checker for every checker in the list, excluding the last one.
Still can't find the way to use Stream API here :)
回答1:
Using IntStream.range
:
IntStream.range(1, checkers.size())
.forEach(i -> checkers.get(i-1).setNextChecker(checkers.get(i)));
or using a for loop:
for (int i = 1; i < checkers.size(); i++)
checkers.get(i-1).setNextChecker(checkers.get(i));
回答2:
A crazy alternative:
Iterator<Checker> currentIt = checkers.subList(0, checkers.size() - 1).iterator();
Iterator<Checker> nextIt = checkers.subList(1, checkers.size()).iterator();
while (currentIt.hasNext()) {
currentIt.next().setNextChecker(nextIt.next());
}
I guess that you could also write it with a single iterator:
Iterator<Checker> it = checkers.iterator();
Checker previous = it.next();
while (it.hasNext()) {
previous.setNextChecker(previous = it.next());
}
But assuming your list is small, and RandomAccess
, I'd just stick with an index-based loop:
for (int i = 0; i < checker.size()-1; ++i) {
checkers.get(i).setNextChecker(checkers.get(i+1));
}
Streams aren't really a benefit here.
来源:https://stackoverflow.com/questions/50006972/replace-for-each-loop-with-lambda-expression