Java forEach continue
continue inside loop is not supported by forEach. As a workaround you can return from the loop.
1) Java 8 forEach continue
// shows how to continue in a forEach loop import java.util.ArrayList; import java.util.List; public class TestClass { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); fruits.add("mango"); fruits.add("apple"); fruits.add("pineapple"); fruits.add("orange"); fruits.stream().forEach(str -> { if (str.equals("pineapple")) { return; } System.out.println(str); }); } }
Output :
mango apple orange
2) Java 8 forEach break
// shows how to break out of forEach loop import java.util.ArrayList; import java.util.List; public class TestClass { public static void main(String[] args) { try { List<String> fruits = new ArrayList<>(); fruits.add("mango"); fruits.add("apple"); fruits.add("pineapple"); fruits.add("orange"); fruits.stream().forEach(fruit -> { if (fruit.equals("pineapple")) { throw new RuntimeException(); } System.out.println(fruit); }); } catch (Exception e) {} } }
Output :
mango apple
References : https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-