Understanding the FindAny Method

Understanding the FindAny Method

Learn how to use the findAny method in java.util.Stream. This returns an Optional describing an element, or an empty Optional if Stream is empty.

Also, remember that the same stream cannot be operated upon with multiple methods after a complete iteration.

import java.util.Optional;import java.util.stream.Stream;public class StreamsFindAny {   public static void main(String[] args)    {      StreamsFindAny streamsFindAny = new StreamsFindAny();      streamsFindAny.proceed();   }   public void proceed()    {      Stream stream = Stream.of("1","5","10");      Optional findAnyOutput = stream.findAny();      System.out.println("FindAny output: " + findAnyOutput);      //If you fail to reinitialize the stream again (as below), you will end up in an Exception case since the stream has already been operated in the previous lines.      //Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed      stream = Stream.of("1","5","10");      long streamCount = stream.count();      System.out.println("Count of elements in stream: " + streamCount);   }}/*

Expected output:

[[email protected]]# java StreamsFindAnyFindAny output: Optional[1]Count of elements in stream: 3*/
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several