$show=/label

How to Break or return from Java Stream forEach

SHARE:

A quick guide to how to use a break or return statement in Java 8 Stream Custom forEach() method. Examples on takeWhile(Predicate p) and Custom forEach implementation

1. Introduction


In this tutorial, You'll learn how to use a break or return in Java 8 Streams when working with the forEach() method.

Java 8 forEach() method takes consumer that will be running for all the values of Stream.

Once forEach() method is invoked then it will be running the consumer logic for each and every value in the stream from a first value to last value.

java 8 custom forEach() methd for Stream API


For each keeps the code very clean and in a declarative manner.

But, when you working with a traditional loop, you can use a break or return from loop based on a condition.

How to Break or return from Java Stream forEach


But, you might have noticed that missing equivalent break or return statement to stop the loop execution based on a condition.

If the stream is an extremely long one then you need to traverse till last value to end the loop.

Our requirement is to stop the loop once out condition is met then forEach does not much help on this.

There are few ways to do even using Java 8 and java 9 API techniques or methods.


2. Java 8 Stream filter() - does not work

Java 8 Break or Return Stream forEach


filter() method which does not work well in our case.

Let us write an example program using filter() method on the stream of Strings.

Print the values until its length matches to greater than 3. If it founds match then skip the remaining.

First of all, we'll show you how to do with stream and then normal for loop example.


package com.javaprogramto.java8.streams.foreach;

import java.util.Arrays;
import java.util.List;

public class StreamFilterBreak {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("one", "two", "three", "seven", "nine", "ten");

        list.stream().filter(s -> s.length() <= 3).forEach(value -> System.out.println(value));
    }
}

Output:

[one
two
ten]

Actually, it should print only the "one", "two" and not print "ten".

But this approach does not work when we try to replace this with the normal for a loop as below.

package com.javaprogramto.java8.streams.foreach;

import java.util.Arrays;
import java.util.List;

public class StreamForBreak {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("one", "two", "three", "seven", "nine", "ten");

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).length() > 3) {

                break;
            }
            System.out.println(list.get(i));

        }

    }
}

Output:

[one
two]

This code works well but with the usage of stream filter() method which does not fulfill our requirement.

3. Using java 9 Stream.takeWhile()


Further, Java 9 API has equipped with a developer handy method to avoid running unnecessary loops once our condition is met.

New stream api introduced with takeWhile(Predicate<T> p) method which stops once the condition is met then it stops iterating through the remaining elements. So, it returns a new Stream until the condition is met.

This method same as break or return statement in java 9 API.

package com.javaprogramto.java8.streams.foreach;

import java.util.Arrays;
import java.util.List;

public class StreamTakeWhile {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");

        list.stream().takeWhile(value -> value.length() > 3).forEach(value -> {
            if (value.length() > 3) {
                System.out.println(value);
            }
        });
    }
}

This code produces the following output of what we are interested in.

[one
two]

If you are not using java 9 version then it is out of the box for you to use. So let us move to the next section.

4. Custom forEach() loop in java 8


Additionally, We can achieve the same with the help of custom foreach concept.

Let us build the custom forEach() method that works the same as takeWhile().

This is implemented using SplitIterator.tryAdvance() method.

package com.javaprogramto.java8.streams.foreach;

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

public class CustomForEachImpl {

    public static class Break {
        private boolean doBreak = false;

        public void stop() {
            doBreak = true;
        }

        boolean get() {
            return doBreak;
        }
    }

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

        while (hadNext && !breaker.get()) {
            hadNext = spliterator.tryAdvance(elem -> {
                consumer.accept(elem, breaker);
            });
        }
    }
}

Use our new forEach() method from CustomForEachImpl class.

This is a little tricky but if you are strong in core java then you can easily understand the logic inside out custom forEach() method.

Especially, the custom forEach() method takes two arguments.

The first argument is Stream<T> and the second is BiConsumer which takes T and Break instance.

This BiConsumer will play a crucial role in when you call this method

Let us jump into, how can you call this with example.

The CustomForEach logic can be used for return statement also. One the condition is met then stop or skip the next all values in the stream. This will reduce the overhead in processing very large streams.

package com.javaprogramto.java8.streams.foreach;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomForEachExample {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("one", "two", "three", "seven", "nine", "ten");

        List<String> output = new ArrayList<>();
        CustomForEachImpl.forEach(list.stream(), (str, breaker) -> {

            if (str.length() > 3) {
                breaker.stop();
            } else {
                output.add(str);
            }

        });

        System.out.println("custom foreach output: "+output);

    }
}

Output

[custom foreach output: [one, two]]

5. Conclusion


In conclusion, you've seen how can we take forEach to next advance level with the help of SplitIterator to get the functionality of break or return in-stream forEach() loop.

Building the Custom ForEach() method with an example.

Example with Java 9 Stream api takeWhile() method.


All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,71,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,7,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How to Break or return from Java Stream forEach
How to Break or return from Java Stream forEach
A quick guide to how to use a break or return statement in Java 8 Stream Custom forEach() method. Examples on takeWhile(Predicate p) and Custom forEach implementation
https://1.bp.blogspot.com/-81--WcmJXTw/Xrr9HhF4QcI/AAAAAAAACt8/uuL8-lHpAYgWnXKO39gtMYzGlne0jMN8QCLcBGAsYHQ/s640/java%2B8%2Bcustom%2BforEach%2528%2529%2Bmethd%2Bfor%2BStream%2BAPI-min.png
https://1.bp.blogspot.com/-81--WcmJXTw/Xrr9HhF4QcI/AAAAAAAACt8/uuL8-lHpAYgWnXKO39gtMYzGlne0jMN8QCLcBGAsYHQ/s72-c/java%2B8%2Bcustom%2BforEach%2528%2529%2Bmethd%2Bfor%2BStream%2BAPI-min.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/java-break-return-stream-foreach.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/java-break-return-stream-foreach.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content