Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaIntermediate Methods of Stream in Java

Intermediate Methods of Stream in Java

The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The method provided by the stream are broadly categorized as

  • Intermediate Methods
  • Terminal Methods

Here, we will be discussing the Intermediate methods of the Stream API. All these methods are in java.util.stream.Stream. Intermediate operators do not execute until a terminal operation is invoked, i.e. they are not executed until a result of processing is actually needed. We will be discussing a few of the important and most frequently used: 

  1. filter(predicate) Method 
  2.  sorted() Method 
  3. distinct() Method 
  4. map() Method

Method 1: filter(predicate) 

It returns a new stream consisting of the elements of the stream from which it is called which are according to the predicate (condition).

Note: 

  • Intermediate functions return a stream back.
  • On any stream you can execute any number of intermediate operations, but the terminal operation should be single and written at last. So following are the intermediate methods provided by the Stream
  • Predicate is a non-interfering, stateless predicate to apply to each element to determine if it should be included or not.

Example

Java




// Java Program to illustrate Intermediate Methods of Streams
// Case 1: filter(predicate) Method
  
// Importing input output classes
import java.io.*;
// Importing List Class from java.util package 
import java.util.List;
 
// Main Class
public class GFG {
   
    // Main driver method
    public static void main (String[] args) {
       
      // Creating an object of List Class by
      // declaring a list of Integers
       
      // Custom entries in the list elements
      List<Integer> intList = List.of(15,20,48,63,49,27,56,32,9);
       
      // Calling the function to
      // print the list of Even numbers
      printEvenNumber(intList);
    }
   
  // Method 2
  // Helper method
  // To print the even numbers using filter method.
  private static void printEvenNumber(List<Integer> intList){
     
        // Display message
        System.out.print("\nEven numbers are : ");
         
        // Illustrating filter method usage 
        intList.stream().filter(
          element -> (element%2==0)
        )
        .forEach(
          element -> System.out.print(element+ " ")
        );
         
    }
}


Output

Even numbers are : 20 48 56 32 

Method 2: sorted()

Returns a stream consisting of the elements of the stream passed, sorted according to the natural order.  If the elements of this stream are not comparable, a  java.lang.ClassCastException may be thrown when the terminal operation is executed.

Example

Java




// Java Program to illustrate Intermediate Method of Stream
// Case 2: sorted() Method
 
// Importing input output class
import java.io.*;
// Importing List class from java.util package
import java.util.List;
 
// Main class
class GFG {
 
    // Method 1
    // To print the elements of the Sorted List
    public static void
    printSortedList(List<Integer> intList)
    {
 
        // Sorts and returns the stream to the forEach
        // illustrating stream method
        intList.stream().sorted().forEach(
            element -> System.out.println(element));
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of List class
        // Declaring object of Integer type
 
        // Custom entries
        List<Integer> intList
            = List.of(68, 45, 99, 21, 8, 76, 34, 19);
 
        // Display message only
        System.out.println(
            "Elements of Sorted List are as follows : ");
 
        // Calling the method to print the Sorted List
        printSortedList(intList);
    }
}


Output

8
19
21
34
45
68
76
99

Method 3: distinct()

It returns a stream consisting of the distinct(different) elements of the passed stream. For ordered stream, the selection of the distinct elements is stable (For duplicated elements, the element appearing first in the encounter order is preserved). While for non-ordered streams it does not make any guarantee for stability.

Example 

Java




// Java Program to illustrate Intermediate Method of Stream
// Case 3: distinct() Method
 
// Importing input output classes
import java.io.*;
// Importing List class from java.util package
import java.util.List;
 
// Main Class
class GFG {
 
    // Method 1
    // To find distinct elements from the List
    public static void
    findDistinctElements(List<Integer> intList)
    {
        intList.stream().distinct().forEach(
            element -> System.out.print(element + " "));
 
        // Display message only
        System.out.println("\n\nSorted List is ");
 
        // Also we are sorting elements at the same time
        intList.stream().distinct().sorted().forEach(
            element -> System.out.print(element + " "));
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of List class
        // Declaring object of Integer type
 
        // Custom integer inputs
        List<Integer> intList
            = List.of(12, 54, 63, 12, 7, 98, 63, 54, 72);
 
        // Calling the Method 1 as above created to
        // find the distinct elements from the list
        findDistinctElements(intList);
    }
}


Output

12 54 63 7 98 72 

Sorted List is 
7 12 54 63 72 98 

Method 4: map()

Mapper is a non-interfering, stateless function to apply to each element of the stream. It returns a stream consisting of the results of applying the given function to the element of the passed stream.

Syntax: 

stream().map(mapper)

Implementation: 

Example  

Java




// Java Program to illustrate Intermediate Stream Methods
// Case 4: map() Method
 
// Importing input output class
import java.io.*;
// Importing List class from the java.util package
import java.util.List;
 
// Main Class
class GFG {
 
    // Method 1
    // To find the cube of elements in the List
    public static void findTheCube(List<Integer> intList)
    {
 
        intList.stream()
            .map(element -> element * element * element)
            .forEach(
                element -> System.out.print(element + " "));
 
        // Display message only
        System.out.println(
            "\n\nOutput after distinct() implementation : ");
 
        // Applying distinct() on this
        intList.stream()
            .distinct()
            .map(element -> element * element * element)
            .forEach(
                element -> System.out.print(element + " "));
 
        // Display message only
        System.out.println(
            "\n\nOutput after sorted() implementation : ");
 
        // Now applying sorted() on this
        intList.stream()
            .distinct()
            .sorted()
            .map(element -> element * element * element)
            .forEach(
                element -> System.out.print(element + " "));
 
        // Display message only
        System.out.println(
            "\n\nOutput after filter() implementation : ");
 
        // Applying Filter() that values
        // only below 10000 will be printed
        intList.stream()
            .distinct()
            .sorted()
            .map(element -> element * element * element)
            .filter(element -> element < 10000)
            .forEach(
                element -> System.out.print(element + " "));
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of List class and
        // declaring object of Integer type
 
        // Custom entries
        List<Integer> intList
            = List.of(5, 19, 8, 23, 6, 54, 32, 5, 23);
 
        // Calling the Method1 in the main() body
        // to get the cube of the elements in the List
        findTheCube(intList);
    }
}


Output

125 6859 512 12167 216 157464 32768 125 12167 

Output after distinct() implementation : 
125 6859 512 12167 216 157464 32768 

Output after sorted() implementation : 
125 216 512 6859 12167 32768 157464 

Output after filter() implementation : 
125 216 512 6859 

 

RELATED ARTICLES

Most Popular

Recent Comments