2

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 :)

5
  • 1
    I would leave it with a for loop. Better readable and I see no advantage of streams here. Commented Apr 24, 2018 at 19:02
  • @lexicore is this any better in terms of readability stackoverflow.com/questions/50006972/… ? Commented Apr 24, 2018 at 21:23
  • @Aominè I really don't see why it should be better than a simple for-loop. Commented Apr 24, 2018 at 21:28
  • @lexicore good shout, I guess I was more focused on using streams as the OP requested for it. Commented Apr 24, 2018 at 21:30
  • @Aominè You're absolutely correct, this was the OPs question and you gave a good answer. Commented Apr 24, 2018 at 21:32

2 Answers 2

5

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Also one could write a for-loop without get(i).
@lexicore I am assuming you mean the for-each loop or also known as the enhanced for loop ?, if so wouldn't that make things a little bit less readable than the current for loop?
Thanks, that's something I was looking for) I agree, that Stream API is not the best choice here, but I was not able to find that solution fast, so I asked this question here.
1

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.

2 Comments

previous.setNextChecker(previous = it.next()); Seems crazy too :)
@user7 yes, it's confusing enough that I had to try it to convince myself it would evaluate correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.