x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    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

    break from loop is not supported by forEach. If you want to break out of forEach loop, you need to throw Exception.
    // 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-


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This