Tuesday 19 September 2017

Whether we can reuse the Stream or not | Java 8 streams | Streams in Java 8


Click here to watch in Youtube :
https://www.youtube.com/watch?v=6_6ytShUcJU&list=UUhwKlOVR041tngjerWxVccw

StreamDemo.java
import java.util.Optional;
import java.util.stream.Stream;

public class StreamDemo
{
    public static void main(String[] args)
    {

        Stream<String> stream = Stream.of("a", "b", "c");               

        Optional<String> anyElement = stream.findAny();

        System.out.println("anyElement = " + anyElement);

        /*
         * Attempt to reuse the same reference after calling the
         * terminal operation will trigger the IllegalStateException.
         * 
         * As the IllegalStateException is a RuntimeException, a
         * compiler will not signalize about a problem. So, it is very
         * important to remember that Java 8 streams can’t be reused.
         * 
         * This kind of behavior is logical because streams were
         * designed to provide an ability to apply a finite sequence
         * of operations to the source of elements in a functional
         * style, but not to store elements.
         */
        Optional<String> firstElement = stream.findFirst();
        System.out.println("firstElement = " + firstElement);
    }

}
Output
anyElement = Optional[a]
Exception in thread "main" java.lang.IllegalStateException: 
stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.findFirst(Unknown Source)
    at StreamDemo.main(StreamDemo.java:28)

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_reuse_stream_exe.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_reuse_stream_exe

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/adf72ea7a150b1a34af5820c19f2232b522614b9/BasicJava/StreamDemo_reuse_stream_exe/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment