0

I am trying to iterate over a TreeMap in java using the forEach loop in Java 8. I want break out of the loop when max == v but i am getting an error "break cannot be used outside of a loop or a switch". Here's a section of the code.

tm.forEach(
            (k,v)->{
                if(max == v)
                {
                    System.out.print(k + " "+ v);
                    break;
                }
            }
            );

So my question is Can we use break statement inside forEach loop and if yes then what is the mistake i am doing?
I am using eclipse Neon with Java8.

greg-449
  • 109,219
  • 232
  • 102
  • 145
Why So Serious
  • 129
  • 1
  • 9
  • 5
    You cannot use break. If you need `break` functionality, you need to use an actual `for` loop. There's probably a dupe for this. – Carcigenicate Feb 21 '20 at 14:30
  • 2
    The closest you can come is in Java 9, with takeWhile. `foo.entrySet().stream().takeWhile(e -> max != e.getValue()).forEach(e -> System.out.print(e.getKey() + " "+ e.getValue()));` – Michael Feb 21 '20 at 14:37
  • 1
    @Michael the OP’s code only prints the first match, so `filter(…) .findFirst() .ifPresent(…)` would do. No need for `takeWhile`. – Holger Feb 21 '20 at 15:43

0 Answers0