Monday, 21 August 2017

Java 8 Stream short circuit operations examples | Streams in Java 8


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

StreamDemo1.java
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Short-circuit operation - anyMatch().
 *
 */
public class StreamDemo1
{
    public static void main(String[] args)
    {
        List<String> nameList = new ArrayList<>();
        nameList.add("Amitabh");
        nameList.add("Shekhar");
        nameList.add("Aman");
        nameList.add("Rahul");
        nameList.add("Shahrukh");
        nameList.add("Salman");
        nameList.add("Yana");
        nameList.add("Lokesh");

        /*
         * This will return true once a condition passed as predicate
         * satisfy. It will not process any more elements.
         */
        boolean matched = nameList.stream()
                .anyMatch((s) -> s.startsWith("S"));

        System.out.println(matched);
    }
}
Output
true
StreamDemo2.java
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Short-circuit operation - findFirst().
 *
 */
public class StreamDemo2
{
    public static void main(String[] args)
    {
        List<String> nameList = new ArrayList<>();
        nameList.add("Amitabh");
        nameList.add("Shekhar");
        nameList.add("Aman");
        nameList.add("Rahul");
        nameList.add("Shahrukh");
        nameList.add("Salman");
        nameList.add("Yana");
        nameList.add("Lokesh");

        /*
         * It will return first element from stream and then will not
         * process any more element.
         */

        String firstMatchedName = nameList.stream()
                .filter((s) -> s.startsWith("S")).findFirst().get();

        System.out.println(firstMatchedName);
    }
}
Output
Shekhar

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/bc0205890e206d66c03b068b168e05c78f68f50d/BasicJava/StreamDemo_shortcircuit_op_examples_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
  • Google+ Followers

    Google+ Badge