Monday, 23 October 2017

How to use the Intermediate operations[filter, map and sorted] of Java 8 Stream | Streams in Java 8

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

/**
 * Intermediate operation : filter()
 */
public class StreamDemo1
{
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("Welcome", "apple", "to", "India");

        /*
         * filter() operation helps eliminate elements based on certain
         * criteria.
         */
        list.stream().filter(element -> !"apple".equals(element))
                .forEach(element -> System.out.println(element));
    }

}
Output
Welcome
to
India

StreamDemo2.java
import java.util.Arrays;
import java.util.List;

/**
 * Intermediate operation : map()
 */
public class StreamDemo2
{
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("Welcome", "apple", "to","India");

        /*
         * map() operation helps map elements to the corresponding
         * results.
         */
        list.stream().filter(element -> !"apple".equals(element))
                .map(String::toUpperCase)
                .forEach(System.out::println);
    }

}
Output
WELCOME
TO
INDIA

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

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

        /*
         * sorted() operation helps sort elements based on certain
         * criteria.
         */
        list.stream().sorted().filter((element) -> !element.startsWith("D"))
                .map(String::toUpperCase)
                .forEach(System.out::println);
    }

}
Output
APPLE
BALL
CAT

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

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

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