LongStream findAny() method in Java

Java 8Object Oriented ProgrammingProgramming

<p>The findAny() method of the LongStream class in Java returns an OptionalLong describing some element of the stream, or an empty OptionalLong if the stream is empty.</p><p>The syntax is as follows:</p><pre class="prettyprint notranslate">OptionalLong findAny()</pre><p>Here, OptionalLong is a container object which may or may not contain a long value.</p><p>To use the LongStream class in Java, import the following package:</p><pre class="prettyprint notranslate">import java.util.stream.LongStream;</pre><p>The following is an example to implement LongStream findAny() method. The isPresent() method of the OptionalLong class returns true if the value is present:</p><h2>Example</h2><pre class="prettyprint notranslate">import java.util.OptionalLong; import java.util.stream.LongStream; public class Demo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; LongStream longStream = LongStream.of(50000L, 70000L, 85000L, 90000L, 95000L).parallel(); &nbsp; &nbsp; &nbsp; longStream = longStream.filter(a &rarr; a &gt; 75000L); &nbsp; &nbsp; &nbsp; OptionalLong res = longStream.findAny(); &nbsp; &nbsp; &nbsp; if (res.isPresent()) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(res.getAsLong()); &nbsp; &nbsp; &nbsp; } else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Nothing!&quot;); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">85000</pre>
Updated on 30-Jul-2019 22:30:25