Wednesday 23 August 2017

How to prove Java 8 Stream is lazy | Java 8 streams tutorial | Java 8 streams | Streams in Java 8


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

Click the below Image to Enlarge
How to prove Java 8 Stream is lazy | Java 8 streams tutorial | Java 8 streams | Streams in Java 8 
StreamDemo1.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamDemo1
{
    public static void main(String[] args)
    {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8,9);

        // get List from Stream Operation
        List<String> result = numbers.stream()
                .filter(i -> (i % 2) == 0).map(i -> "[" + i + "]")
                .collect(Collectors.toList());

        System.out.println(result);

    }
}
Output
[[2], [4], [6], [8]]

StreamDemo2.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo2
{
    public static void main(String[] args)
    {
        List<Integer> newNumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Stream<Integer> lazyStream = newNumbers.stream().filter(i -> {
            System.out.println("filter: [" + i + "]");
            return (i % 2) == 0;
        }).map(i -> {
            System.out.println("map: [" + i + "]");
            return i;
        });

        for (int i = 1; i <= 3; i++)
        {
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("running... " + i + " sec");
        }

        System.out.println("Going to call collect method..");
        System.out.println("---------------------------------\n");
        /*
         * System only activates the command inside filter and map
         * method after we call collect method.
         */
        lazyStream.collect(Collectors.toList());

    }
}
Output
running... 1 sec
running... 2 sec
running... 3 sec
Going to call collect method..
---------------------------------

filter: [1]
filter: [2]
map: [2]
filter: [3]
filter: [4]
map: [4]
filter: [5]
filter: [6]
map: [6]
filter: [7]
filter: [8]
map: [8]
filter: [9]

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/bc0205890e206d66c03b068b168e05c78f68f50d/BasicJava/StreamDemo_Lazy_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