The forEach methods, like Iterable.forEach , Iterator.forEachRemaining or Stream.forEach are designed to do what the name suggests, apply an action to each element, not just some.
Stopping the iteration is not supported by this API, which can be recognized by looking at the functional signature of the Consumer interface, which (T) -> void , does not contain any possibility for the collection or iterator to notice the stopping condition.
At this point you should reconsider whether you are using the right tool for the job. Compare your approach e.g.
List<String> names = Arrays.asList("A", "B", "C"); int ix = names.indexOf("B"); (ix<0? names: names.subList(0, ix)).forEach(System.out::println); if(ix>=0) System.out.println("Found"); System.out.println("AfterIter");
Of course, if printing elements was for debugging purposes only, the actual operation is simplified to
List<String> names = Arrays.asList("A", "B", "C"); if(names.contains("B")) System.out.println("Found"); System.out.println("AfterIter");
If equality was only a placeholder for an arbitrary predicate, you can use
List<String> names = Arrays.asList("A", "B", "C"); if(names.stream().anyMatch(s -> s.equals("B"))) System.out.println("Found"); System.out.println("AfterIter");
which can be adapted to arbitrary conditions.
It can be expanded to
List<String> names = Arrays.asList("A", "B", "C"); Optional<String> match = names.stream() .peek(System.out::println) .filter(Predicate.isEqual("B")) .findFirst(); if(match.isPresent()) System.out.println("Found"); // or match.ifPresent(s -> System.out.println("Found "+s)); System.out.println("AfterIter");
shows how you can debug processing by printing elements, an alternative way to express an equality predicate (you can still replace it with other predicates) and how to get the actual corresponding element for non-trivial predicates.
Generally, if you want to use the new Java 8 APIs, don't try to write your logic in terms of forEach . Rather, try to avoid forEach , using more appropriate operations if possible.