The Wayback Machine - https://web.archive.org/web/20240930234047/https://www.geeksforgeeks.org/functional-programming-in-java-8-using-the-stream-api-with-example/
Open In App

Functional Programming in Java 8+ using the Stream API with Example

Last Updated : 09 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

API is an acronym for Application Programming Interface, which is software and the java streams work on a data source. Consider a stream like a flow of water in a small canal. Let’s take a real-life example. Each time a user uses an application that is popular these days like WhatsApp in order to communicate via delivering text messages or calls to other users. Both users are using an API.

Java streams work on three operations which as mentioned below 

  1. Data Source
  2. Intermediate operation
  3. Terminal operation

Methods: Streams can be created in three ways

  1. Using an object of any class from the collection framework
  2. Using an array of the reference data type
  3. Using the interface defined in the ‘java.util.stream’ package

Method 1: Data Source 

The data source can be widely varied such as an array, List, etc 

Syntax: 

ArrayList<Integer> numbers = new ArrayList<>();
Integer[] numbers = {1,2,3};

Example 1: Using an object as a data source

Java




// Java Program showcasing data source
// using an object as a data source
 
// Importing input output classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Data Source
 
        // Creating an arrayList object
        // Declaring object of String type
        ArrayList<String> gfgNames = new ArrayList<>();
 
        // Custom input elements to above object
        gfgNames.add("Dean");
        gfgNames.add("castee");
        gfgNames.add("robert");
 
        // Creating object of Stream where Stream is created
        // using arrayList and object as data source
        Stream<String> streamOfNames = gfgNames.stream();
 
        // Print and display element
        System.out.print(streamOfNames);
    }
}


 
Example 2: Using an array as a data source

// Data Source
Integer[] numbers = {1,2,3,4,5};
// Stream using an array
Stream<Integer> streamOfNumbers = Arrays.stream(numbers);
// using predefined Instream interface
integerStream = IntStream.range(1,100); // a stream from 1 to 99;

Java




// Java Program showcasing data source
// using an array as a data source
 
// Importing java input output class
import java.io.*;
 
// Importing all classes from
// java.util package
import java.util.*;
 
// Importing class for additional operations,
// additionls and pipelines
import java.util.stream.IntStream;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a predefined stream using range method
        // Custom inputs for range as parameters
        var stream = IntStream.range(1, 100);
 
        // Stream is created
        var max = stream.filter(number -> number % 4 == 0)
                      .count();
 
        // Print and display the maximum number
        // from the stream
        System.out.println(max);
    }
}


24

Method 2: Intermediate Operation

Intermediate operations are some methods that one can apply on a stream. 

Note: It can be of any number

filter()

Example:

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // Data Source
        Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }
 
        // Stream
        Stream<Integer> streamOfNumbers
            = Arrays.stream(numbers);
 
        // filter all the even numbers
        Stream<Integer> evenNumbersStream
            = streamOfNumbers.filter(
                number -> number % 2 == 0)
    }
}


 
Method 3: Terminal operation

Terminal operation methods that we can apply on a stream that will cause a stream to be “closed”.

Concept: 

Some terminal operations can be used to iterate on the elements of the stream.

min(),max(),count()
forEach(),noneMatch()

Example 1: Explaining stream API

Java




// Importing input output classes
import java.io.*;
// Importing all classes from
// java.util package
import java.util.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Data source
        // Custom integer inputs
        Integer[] numbers
            = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
 
        // Stream
        var streamOfNumbers = Arrays.stream(numbers);
 
        // Using filter method
        var evenNumbersStream
            = streamOfNumbers
                  .filter(number -> number % 3 == 0)
                  .count();
 
        // Print and display
        System.out.println(evenNumbersStream);
    }
}


Output

4

Example 2:

Java




// Importing all classes from java.util package
import java.io.*;
import java.util.*;
 
// Class
class GFG {
 
  // Main driver method
    public static void main(String[] args)
    {
      // Creating an ArrayList of Integer type
        ArrayList<Integer> list = new ArrayList<>();
       
      // Adding elements to above object of Arraylist
      // Custom inputs
        list.add(20);
        list.add(4);
        list.add(76);
        list.add(21);
        list.add(3);
        list.add(80);
 
        var stream = list.stream();
 
        var numbers
            = stream.filter(number -> number % 2 == 0)
                  .filter(number -> number > 20);
       
      // Print all the elements of the stream on the console
        numbers.forEach(System.out::println);
    }
}


Output

76
80

Note: One can pass lambda also number -> System.out.println(number + ” “)



Previous Article
Next Article

Similar Reads

Java Program to Convert String to Char Stream Without Using Stream
Char stream defines the array of characters. In this article, we will learn the different types of methods for converting a String into a char stream in Java without using Stream. Let us see some methods one by one. ExamplesInput: String = HelloGeeksOutput: [H, e, l, l, o, G, e, e, k, s] Input: String = Introduction Output: [I, n, t, r, o, d, u, c,
4 min read
Spring Cloud Stream - Functional and Reactive
Spring Cloud Stream is a Spring framework that simplifies creating event-driven microservices. It uses functional programming constructs for message processing logic, often using annotated methods within a class and reactive programming tools like Reactor for asynchronous and reactive processing. Maven Dependencies<dependency> <groupId>
3 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
Functional Programming in Java with Examples
So far Java was supporting the imperative style of programming and object-oriented style of programming. The next big thing what java has been added is that Java has started supporting the functional style of programming with its Java 8 release. In this article, we will discuss functional programming in Java 8. What is functional programming? It is
9 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Count occurrence of a given character in a string using Stream API in Java
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in str. Approach: Convert the string into char
1 min read
Java Stream API – Filters
In this article, we will learn Java Stream Filter API. We will cover, 1. How stream filter API works. 2. Filter by Object Properties. 3. Filter by Index. 4. Filter by custom Object properties. Stream Filter API Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argument of any type and returns Boolean. The element wi
5 min read
concat() Method of Stream Interface in Java API
Stream Interface in Java API is present in Java.Util.Stream and is extending the BaseStream<T, Stream<T>> interface. This interface is created on any stream of objects and it provides a lot of methods that can be used to modify the stream of those objects. concat() Method: The name of the method suggests this method is mainly used to co
3 min read
Implement Secure Hashing Algorithm - 512 ( SHA-512 ) as Functional Programming Paradigm
Given a string S of length N, the task is to find the SHA-512 Hash Value of the given string S. Examples: Input: S = "GeeksforGeeks"Output: acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c Input: S = "hello world"Output:309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bc
15 min read
Find N'th Highest Salary Using Stream API
Consider a scenario where you have a dataset containing various salary values, and you need to find the Nth highest salary. This task might arise in applications ranging from financial systems to human resources, where understanding salary distributions is crucial. For Data Manipulation and Processing, Java's Stream API has proven to be a powerful
4 min read
Functional Interfaces in Java
Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a
10 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supp
2 min read
Program to convert a Set to Stream in Java using Generics
Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are the various methods to convert Set to St
3 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Initialize a list in a single line with a specified value using Java Stream
Given a value N, the task is to create a List having this value N in a single line in Java using Stream. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate the Stream using generate() method Set the size of the List to be created as 1 using limit() method Pass the value to be mappe
2 min read
Java Program to Find Maximum Odd Number in Array Using Stream and Filter
Java 8 introduced some great features like Stream and Filter which tremendously simplify tasks like reading data and performing operations like minimum, maximum, sum, and conditional check on them. In this program, we will get the maximum of all odd numbers from a list of integers with the help of the Java Stream and Filter method. Using Loops In t
3 min read
How to Convert String to Char Stream in Java without Using Library Functions?
In Java, we can convert a string to a char stream with a simple built-in method .toCharArray(). Here, we want to convert the string to a char stream without using built-in library functions. So, we will create an empty char array iterate it with string characters, and store the individual characters from the string to the char array one after the o
2 min read
Reactive Programming in Java with Example
Java reactive programming refers to a programming paradigm that focuses on building responsive and scalable applications that can handle concurrent and asynchronous tasks efficiently. Reactive programming is based on the principles of the reactive manifesto, which includes characteristics such as responsiveness, elasticity, resilience, and message-
6 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.concat() in Java
Stream.concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. Syntax : static <T> Stream<T> concat(Str
4 min read
Stream.distinct() in Java
distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not neces
2 min read
Stream sorted() in Java
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Syntax
2 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
Stream generate() method in Java with examples
Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of s
1 min read