Streams in java8

              A collection of elements processed in sequential order in a functional way. The situation has a collection of classes, interfaces and enum type of elements. The built in package used for stream is

“java.util.stream”

How to create an object for stream?

Stream st = c.Stream();

Where c is a collection.

Basic components of a stream is listed below.

  • ·       Source code.
  • ·       Sequence of elements
  • ·       Aggregate operations
  • ·       Pipelining
  • ·       Internal iteration

                                                           Pipeline


                                                            

·       The process is making the source code into the pipeline in a sequence manner. The sequential can be iterated also.

·       Input is a collection of objects. It may be an array, collection or an IO channel.

Stream Operations: Filter, Map, and Reduce:

              There are three operations in Stream operations. Filter, Map and Reduce.

Map: This method uses lambda expression as argument. It changes the individual element and return as new stream object.

Filter:  This method also uses lambda expression as its argument.

Reduction: It is an operation to process the elements and produce the result. This is the final step. So, it is called as terminal operations. Eg: Sum of numbers, Average of the given numbers.

Java Program to perform Stream operations:

  • ·       This program starts with importing two packages. Java.io, java.util.
  • ·       Create a class “OddCheck” and save it as “OddCheck.java”.
  • ·       Inside the main() function,  create a arraylist l1.
  • ·       Add the element to arraylist l1.
  • ·       Print the array of elements before processing.
  • ·       Use the lambda function  and filter function for odd number checking and store it into list ls.
  • ·       Finally, print the list with odd numbers.

// Java Program to illustrate stream

import java.io.*;

import java.util.*;

import java.util.stream.*;

// Main class

public class OddCheck {

    // Main method

    public static void main(String[] args)

    {

        // Creating an Array list object of integer type

        ArrayList<Integer> l1 = new ArrayList<Integer>();

        // Inserting elements to l1(list)

        l1.add(45);

        l1.add(4);

        l1.add(9);

        l1.add(22);

        l1.add(19);

        l1.add(36);

        l1.add(11);

         // Printing the list

        System.out.println("The list of elements are :  + l1);

        // Printing a new line space

        System.out.println();

        List<Integer> ls = l1.stream().filter(i -> i % 2 != 0).collect(Collectors.toList());

       //print the list of odd numbers

        System.out.println("Printing the List after stream operation : "+ ls);

    }

}

Here, is the output.

This is the simple way of using java Streams.

No comments:

Post a Comment