Tuesday 29 August 2017

Generate method of Java 8 Stream | Java 8 streams tutorial | Java 8 streams | Streams in Java 8


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

StreamGenerateDemo1.java
import java.util.stream.Stream;

public class StreamGenerateDemo1
{
    public static void main(String[] args)
    {
        String str = "Hello World!";

        /*
         * generate(): We need to pass Supplier to this method and it
         * will return an infinite sequential unordered stream. This
         * is suitable for generating constant streams, streams of
         * random elements, etc.
         */

        Stream<String> stream = Stream.generate(str::toString);                                  
        stream.forEach(s -> System.out.println(s));
    }
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
...
...
...
..

StreamGenerateDemo2.java
import java.util.stream.Stream;

public class StreamGenerateDemo2
{
    public static void main(String[] args)
    {
        String str = "Hello World!";

        /*
         * generate(): We need to pass Supplier to this method and it
         * will return an infinite sequential unordered stream. This
         * is suitable for generating constant streams, streams of
         * random elements, etc.
         * 
         * limit(): We need to pass a max value and it returns the
         * stream up to the max number of elements.
         */

        Stream<String> stream = Stream.generate(str::toString)
                                      .limit(4);
        stream.forEach(s -> System.out.println(s));
    }
}
Output
Hello World!
Hello World!
Hello World!
Hello World!

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/07d37f967453de17efa70af5825dc03ae2d5a7c0/BasicJava/StreamDemo_generate_hw_App/?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