AddThis

Monday 19 October 2020

How to Break from Java Stream forEach Loop

As Java developers, we often write code that iterates over a set of elements and performs an operation on each one. The Java 8 streams library and its forEach method allow us to write that code in a clean, declarative manner.
While this is similar to loops, we are missing the equivalent of the break statement to abort iteration. A stream can be very long, or potentially infinite, and if we have no reason to continue processing it, we would want to break from it, rather than wait for its last element.


In this tutorial, we're going to look at some mechanisms that allow us to simulate a break statement on a Stream.forEach operation.


Java 9's Stream.takeWhile()


Let's suppose we have a stream of String items and we want to process its elements as long as their lengths are odd.

Let's try the Java 9 Stream.takeWhile method:


Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")

.takeWhile(n -> n.length() % 2 != 0)

.forEach(System.out::println);

If we run this, we get the output:


cat

dog

Let's compare this with the equivalent code in plain Java using a for loop and a break statement, to help us see how it works:


List<String> list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck");

for (int i = 0; i < list.size(); i++) {

String item = list.get(i);

if (item.length() % 2 == 0) {

break;

}

System.out.println(item);

}

As we can see, the takeWhile method allows us to achieve exactly what we need.

 

 

 

No comments:

Post a Comment

100 AWS Services in Just One Line Each

  100 AWS Services in Just One Line Each Amazon EC2:  Virtual servers in the cloud. Amazon S3:  Scalable object storage service. Amazon RDS:...