Replace for-each loop with lambda expression

纵然是瞬间 提交于 2021-02-19 06:25:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!