How To Break or Return From Java 8 Stream Foreach – Detailed Guide

Break and Continue statements inside a loop in Java helps to have control over the loop iteration.
This tutorial lets you see different possible ways to Break and Return from Java 8 stream foreach.

Using Return in Foreach

The foreach method doesn’t support the continue statement, but we can skip a loop by simply having a return statement inside the foreach, as shown below.
Code

    public static void main(String[] args) {
        List<String> directions = Arrays.asList("North", "East", "South", "West");  

        directions.forEach(element -> {  
            if (element.equalsIgnoreCase("South")) {  
                return;  
            }  
            System.out.println(element);  
        });
    }

Output

    North
    East
    West

Using Break in Foreach

Usage of break statement in foreach is also not directly supported, but by throwing any exception will stop the loop iteration.
Code

    public static void main(String[] args) {
        List<String> directions = Arrays.asList("North", "East", "South", "West");  
        try {  
            directions.forEach(element -> {  
                if (element.equalsIgnoreCase("South")) {  
                    throw new RuntimeException("condition met");  
                }  
                System.out.println(element);  
            });  
        } catch (Exception exception) {  
        }
    }

Output

    North
    East

Using Java Stream().takeWhile() and Foreach

Java 9 introduced Stream().takeWhile() method, which will only select values in a stream until the condition is satisfied (true).
After the first failure to satisfy the condition(false), all values will be eliminated while iterating a collection.

Stream().takeWhile() is similar to applying a break-in for each statement.

    public static void main(String[] args) {
        List<String> directions = Arrays.asList("North", "East", "South", "West");  

    directions.stream().takeWhile(element -> element.length() > 4).forEach(element -> {  
        System.out.println(element);  
    });
    }

Output

    North

In the above example, all elements are printed until the first failure to satisfy the condition(false) takes place.
In this case, the second element(“East”) fails to satisfy the condition(length>4) and returns false, so all the elements after that condition failure are eliminated.

Using Java Stream and Custom Foreach

You can also create a custom Foreach functionality by creating a method with two parameters (a Stream and a BiConsumer as a Break instance) to achieve break functionality.
Code

    import java.util.Spliterator;  
    import java.util.function.BiConsumer;  
    import java.util.stream.Stream;  

    public class CustomForEach {  

        public static class Break {  
            private boolean isBreak = false;  

            public void executeBreak() {  
                isBreak = true;  
            }  

            boolean getBreak() {  
                return isBreak;  
            }  
        }  

        public static <T> void forEach(Stream<T> stream, BiConsumer<T, Break> consumer) {  
            Spliterator<T> spliterator = stream.spliterator();  
            boolean hadNext = true;  
            Break breakObject = new Break();  

            while (hadNext && !breakObject.getBreak()) {  
                hadNext = spliterator.tryAdvance(element -> {  
                    consumer.accept(element, breakObject);  
                });  
            }  
        }  
    }

    //main method
    public static void main(String[] args) {
        CustomForEach.forEach(directions.stream(), (element, breaker) -> {  

            if (element.equalsIgnoreCase("South")) {  
                System.out.println("Condition met and executing foreach break ");  
                breaker.executeBreak();  

            } else {  
                System.out.println("Printing value:   " + element);  
            }  

        });
    }

Output

    Printing value:   North
    Printing value:   East
    Condition met and executing foreach break

Related Topics

Leave a Comment