Monday 23 October 2017

How to use the Intermediate operations[forEach, collect and count] of Java 8 Stream


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

StreamDemo1.java
import java.util.Arrays;
import java.util.List;

/**
 * Terminal operation : foreach()
 */
public class StreamDemo1
{
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("Ball", "Cat", "Dog", "Apple");

        /*
         * foreach operations helps iterate the elements of the Stream.
         */
        list.stream().sorted().filter((s) -> !s.startsWith("B"))
                .map(String::toUpperCase).forEach(System.out::println);
    }

}
Output
APPLE
CAT
DOG

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

/**
 * Terminal operation : collect()
 */
public class StreamDemo2
{
    public static void main(String[] args)
    {
        Stream<String> stream = Stream.of("Apple", "Ball", "Cat");

        /*
         * collect() operation helps to collect the stream result in a
         * collection like list.
         */
        List<String> list = stream.collect(Collectors.toList());
        System.out.println(list);
    }

}
Output
[Apple, Ball, Cat]

StreamDemo3.java
import java.util.Arrays;
import java.util.List;

/**
 * Terminal Operation : count()
 */
public class StreamDemo3
{
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("Ball", "Dog", "Apple");

        /*
         * count() operation return the aggregate count for stream data.
         */
        long count = list.stream().filter((s) -> s.startsWith("B")).count();

        System.out.println(count);
    }

}
Output
1

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/921a65d57c0ec8a07d5edae78f1552619b89e108/BasicJava/StreamDemo_terminal_op_fcc/?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