0

Say l1 is a data structure that implements Iterable, and assertEquals() was taken from JUnit 5.

I would like to assert that l1 has the elements zero to 99 in order. How can I do this with a lambda and forEach iterate through l1?

(The following code returns an error because counter is not final.)

int counter=0;
l1.forEach(t -> {
    assertEquals(counter,t);
    counter++;
});
thegoodhunter-9115
  • 317
  • 1
  • 3
  • 15
  • 1
    Duplicate aside, you probably should _not_ be using `forEach` with a lambda if you want to just find out how many elements are in your collection. Use the `size()` method instead. – Tim Biegeleisen Sep 27 '20 at 01:46
  • @TimBiegeleisen I would like to check that `l1` has zero to 99 in that order with a forEach and a lambda. Is there a good way to do this? – thegoodhunter-9115 Sep 27 '20 at 01:57
  • 1
    Why does it have to be a `forEach` and a lambda? Part of being a good programmer is to choose the correct tool for the task. `forEach` + lambda is the wrong tool for this task. A regular `for` loop will work just as well, better even, since it doesn't have the limitation the lambda does. – Andreas Sep 27 '20 at 02:05
  • @Andreas I see, thank you. I'm new to Java, Iterators, and Lambdas, and I wanted to see what they could do. Is it possible, though? – thegoodhunter-9115 Sep 27 '20 at 02:18
  • 1
    Possible? Yes. But just because you *can*, doesn't mean you *should*. And you certainly shouldn't. Being new to Java, you should focus on doing it the right way, instead of trying to learn bad behaviors. – Andreas Sep 27 '20 at 02:20

0 Answers0