Home > Java > javaTutorial > body text

How to Break or Return from Java 8 Stream forEachLike Iteration?

Linda Hamilton
Release: 2024-10-24 01:42:02
Original
422 people have browsed it

How to Break or Return from Java 8 Stream forEachLike Iteration?

Breaking or Returning from Java 8 Stream forEach

Like external iteration using enhanced for-each loops, internal iteration with Java 8 lambda expressions requires a different approach for breaking or returning. Breaking out of a for-each loop can be accomplished using the break statement or by returning the current object.

In the case of stream forEach, neither break nor return can be used. The reason for this is that forEach is a terminal operation, meaning it executes a side-effect on each element and does not return any value.

Alternatives for Breaking or Returning from Stream forEach

Instead, one should consider using other stream methods that offer different functionality:

  • filter(): To filter out elements that don't meet a specified condition and obtain a new stream containing the filtered elements.
  • findFirst(): To retrieve the first element that satisfies a given predicate. If no element matches, it returns an empty Optional.
  • anyMatch(): To check if any element matches a certain predicate.
  • collect(): To reduce the stream into a single value, collection, or other result.

Example Code

Using filter() to find the first element that satisfies a condition:

<code class="java">Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findFirst();</code>
Copy after login

Using anyMatch() to determine if any element meets a predicate:

<code class="java">boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);</code>
Copy after login

The above is the detailed content of How to Break or Return from Java 8 Stream forEachLike Iteration?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!