Functional Programming in Java with Examples
Last Updated :
15 Mar, 2023
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 a declarative style of programming rather than imperative. The basic objective of this style of programming is to make code more concise, less complex, more predictable, and easier to test compared to the legacy style of coding. Functional programming deals with certain key concepts such as pure function, immutable state, assignment-less programming etc.
Functional programming vs Purely Functional programming:
Pure functional programming languages don't allow any mutability in its nature whereas a functional style language provides higher-order functions but often permits mutability at the risk of we failing to do the right things, which put a burden on us rather than protecting us. So, in general, we can say if a language provides higher-order function it is functional style language, and if a language goes to the extent of limiting mutability in addition to higher-order function then it becomes purely functional language. Java is a functional style language and the language like Haskell is a purely functional programming language.
Let's understand a few concepts in functional programming:
- Higher-order functions: In functional programming, functions are to be considered as first-class citizens. That is, so far in the legacy style of coding, we can do below stuff with objects.
- We can pass objects to a function.
- We can create objects within function.
- We can return objects from a function.
- We can pass a function to a function.
- We can create a function within function.
- We can return a function from a function.
- Pure functions: A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something.
- Lambda expressions: A Lambda expression is an anonymous method that has mutability at very minimum and it has only a parameter list and a body. The return type is always inferred based on the context. Also, make a note, Lambda expressions work in parallel with the functional interface. The syntax of a lambda expression is:
(parameter) -> body
In its simple form, a lambda could be represented as a comma-separated list of parameters, the –> symbol and the body.
How to Implement Functional Programming in Java?
java
// Java program to demonstrate
// anonymous method
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
// Defining an anonymous method
Runnable r = new Runnable() {
public void run()
{
System.out.println(
"Running in Runnable thread");
}
};
r.run();
System.out.println(
"Running in main thread");
}
}
Output: Running in Runnable thread
Running in main thread

If we look at run() methods, we wrapped it with Runnable. We were initializing this method in this way upto Java 7. The same program can be rewritten in Java 8 as:
java
// Java 8 program to demonstrate
// a lambda expression
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
Runnable r
= ()
-> System.out.println(
"Running in Runnable thread");
r.run();
System.out.println(
"Running in main thread");
}
}
Output: Running in Runnable thread
Running in main thread
Now, the above code has been converted into Lambda expressions rather than the anonymous method. Here we have evaluated a function that doesn't have any name and that function is a lambda expression. So, in this case, we can see that a function has been evaluated and assigned to a runnable interface and here this function has been treated as the first-class citizen.
Refactoring some functions from Java 7 to Java 8:
We have worked many times with loops and iterator so far up to Java 7 as follows:
java
// Java program to demonstrate an
// external iterator
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
// External iterator, for Each loop
for (Integer n : numbers) {
System.out.print(n + " ");
}
}
}
Output: 11 22 33 44 55 66 77 88 99 100
Above was an example of forEach loop in Java a category of external iterator, below one is again example and another form of external iterator.
java
// Java program to demonstrate an
// external iterator
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
// External iterator
for (int i = 0; i < numbers.size(); i++) {
System.out.print(numbers.get(i) + " ");
}
}
}
Output: 11 22 33 44 55 66 77 88 99 100
We can transform the above examples of an external iterator with an internal iterator introduced in Java 8, as follows:
java
// Java 8 program to demonstrate
// an internal iterator
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
// Internal iterator
numbers.forEach(number
-> System.out.print(
number + " "));
}
}
Output: 11 22 33 44 55 66 77 88 99 100
Here, the functional interface plays a major role. Wherever a single abstract method interface is expected, we can pass lambda expression very easily. Above code could be more simplified and improved as follows:
numbers.forEach(System.out::println);
Imperative Vs Declarative Programming:
The functional style of programming is declarative programming. In the imperative style of coding, we define what to do a task and how to do it. Whereas, in the declarative style of coding, we only specify what to do. Let's understand this with an example. Given a list of number let's find out the sum of double of even numbers from the list using an imperative and declarative style of coding.
java
// Java program to find the sum
// using imperative style of coding
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
int result = 0;
for (Integer n : numbers) {
if (n % 2 == 0) {
result += n * 2;
}
}
System.out.println(result);
}
}
The first issue with the above code is that we are mutating the variable result again and again. So mutability is one of the biggest issues in an imperative style of coding. The second issue with the imperative style is that we spend our effort telling not only what to do but also how to do the processing. Now let's re-write above code in a declarative style.
java
// Java program to find the sum
// using declarative style of coding
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
System.out.println(
numbers.stream()
.filter(number -> number % 2 == 0)
.mapToInt(e -> e * 2)
.sum());
}
}
From the above code, we are not mutating any variable. Instead, we are transforming the data from one function to another. This is another difference between Imperative and Declarative. Not only this but also in the above code of declarative style, every function is a pure function and pure functions don't have side effects.
In the above example, we are doubling the number with a factor 2, that is called Closure. Remember, lambdas are stateless and closure has immutable state. It means in any circumstances, the closure could not be mutable. Let's understand it with an example. Here we will declare a variable factor and will use inside a function as below.
java
// Java program to demonstrate an
// declarative style of coding
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
int factor = 2;
System.out.println(
numbers.stream()
.filter(number -> number % 2 == 0)
.mapToInt(e -> e * factor)
.sum());
}
}
Above code works well, but now let's try mutating it after its use and see what happens:
java
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<Integer> numbers
= Arrays.asList(11, 22, 33, 44,
55, 66, 77, 88,
99, 100);
int factor = 2;
System.out.println(
numbers.stream()
.filter(number -> number % 2 == 0)
.mapToInt(e -> e * factor)
.sum());
factor = 3;
}
}
The above code gives a compile-time error saying Local variable factor defined in an enclosing scope must be final or effectively final.
The time complexity of this program is O(n), where n is the number of elements in the list. This is because the program iterates over each element of the list once to apply the filter and map operations.
The space complexity of this program is O(1), because it only stores the input list and a few integers in memory, and the memory usage does not depend on the size of the input list.

This means that here, the variable factor is by default being considered as final. In short, we should never try mutating any variable which is used inside pure functions. Doing so will violate pure functions rules which says pure function should neither change anything nor depend on anything that changes. Mutating any closure(here factor) is considered as a bad closure because closures are always immutable in nature.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read