Stream API Example In Java 8

Stream API are designed to be efficient and can support improving the performance of programs. We can avoid unnecessary loops and iterations in our programs by using Stream functionality. Streams can be used for filtering, collecting, printing, and converting data from one structure to another such as one collection to another collection.

  1. Java 8 introduces Stream API, and some additional features to allows functional-style operations on the elements.
  2. The stream can be used by importing java.util.stream package.
  3. The stream API is used to process collections of objects.
  4. A Stream is a sequence of components that can be processed sequentially.
  5. The elements of a stream are only visited once during the life of a stream.
  6. Stream does not modify the source. It produces a new Stream by filtering or applying any logic.

Syntax:

Stream stream  = collection.strim();

Example of filterig data using stream:


import java.io.*;
import java.util.*;
import java.util.stream.*;

public class StreamFilterExample {
  static void main (String args[]){ 
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    //Filtering the even numbers from a collection
    List<Integer> evenList = 
        Arrays.asList(numbers).stream() 
            .filter(i -> i % 2 == 0)
            .collect(Collectors.toList());
                  
    System.out.println( "Even numbers after stream operation : "+ evenList );          
          
 }
}
 

Output:
    Even numbers after stream operation : [2, 4, 6, 8, 10]