Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Introduction to Functional Programming in Java

Last Updated: 24th March, 2026

8.1 Introduction to Functional Programming in Java

8.1.1 Explanation

Functional programming was introduced to Java through Lambda Expressions and the Streams API (Java 8+). This paradigm shifts from how to do things (imperative) to what to do (declarative). It emp–hasizes writing concise, readable, and parallel-friendly code for data transformation and computation.

Before Java 8, processing collections required verbose loops. Now, developers can perform operations like filtering, mapping, and reducing data with minimal syntax.
Lambda expressions enable passing behavior (functions) as arguments, leading to expressive constructs and reduced boilerplate.

Key benefits of functional programming in Java:

  • Simplifies code and improves readability.
  • Enables efficient parallel computation through the Streams API.
  • Encourages immutable and stateless operations.
  • Reduces side effects and promotes reusability.

This evolution aligns Java with other modern languages like Python and Kotlin, while maintaining type safety and backward compatibility.

8.1.2 Code

import java.util.*;

import java.util.stream.*;

public class FunctionalIntro {

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

// Imperative style

for (int n : numbers) {

if (n % 2 == 0)

System.out.print(n + " ");

}

System.out.println("\n--- Using Streams ---");

// Declarative functional style

numbers.stream()

.filter(n -> n % 2 == 0)

.forEach(System.out::print);

}

}

8.1.3 Example

Output:

2 4 6 8

--- Using Streams ---

2468

Explanation:
The first approach uses a loop with explicit conditions (imperative).
The second uses Streams with Lambda expressions (n -> n % 2 == 0), creating a cleaner, declarative syntax for the same logic.

8.1.4 Use Cases

  • Simplifying collection operations (filtering, mapping).

  • Improving readability in large-scale data transformations.

  • Supporting real-time analytics and parallel data processing.

  • Writing expressive, bug-resistant code.

     

8.1.5 Relevant Table

Feature

Description

Example

Lambda Expression

Function as an argument

x -> x * x

Stream API

Process sequences of data

list.stream()

Filter

Select elements by condition

.filter(x -> x>5)

Map

Transform data

.map(x -> x*2)

Reduce

Aggregate results

.reduce(0, Integer::sum)

8.2 Lambda Expressions

8.2.1 Explanation

Lambda Expression is a short block of code that takes parameters and returns a value, enabling functional-style programming in Java.
It eliminates the need for anonymous inner classes, simplifying event handling, iteration, and asynchronous processing.

Syntax:

(parameters) -> expression

or

(parameters) -> { statements }

Lambdas can be stored in variables, passed to methods, or used inline.
They are primarily used with functional interfaces — interfaces containing a single abstract method, such as Runnable, Comparator, or custom interfaces annotated with @FunctionalInterface.

Java also provides built-in functional interfaces under java.util.function:

  • Predicate<T> – boolean test condition.
  • Function<T,R> – transforms input to output.
  • Consumer<T> – performs action, returns nothing.
  • Supplier<T> – supplies data without input.

This makes Lambda expressions the foundation of modern Java APIs.

8.2.2 Code

import java.util.function.*;

public class LambdaDemo {

public static void main(String[] args) {

Predicate<Integer> isEven = n -> n % 2 == 0;

Function<Integer, Integer> square = n -> n * n;

Consumer<String> printer = s -> System.out.println("Hello, " + s);

Supplier<Double> randomValue = () -> Math.random() * 100;

System.out.println("Is 6 even? " + isEven.test(6));

System.out.println("Square of 5: " + square.apply(5));

printer.accept("Java Developer");

System.out.println("Random Value: " + randomValue.get());

}

}

8.2.3 Example

Output:

Is 6 even? true

Square of 5: 25

Hello, Java Developer

Random Value: 72.345 (approx)

Explanation:
Four lambda expressions are created for different functional interfaces.
Each performs specific operations, demonstrating how behavior can be passed as an argument for flexible program design.

8.2.4 Use Cases

  • Defining custom logic inline for filtering, sorting, and mapping.
  • Simplifying event-driven architectures (GUI listeners, async tasks).
  • Writing clean concurrent or functional data pipelines.
  • Enhancing testability through modular behavior injection.

8.2.5 Relevant Table

Functional Interface

Method

Purpose

Lambda Example

Predicate<T>

test(T t)

Returns boolean

x -> x > 10

Function<T,R>

apply(T t)

Transforms input to output

x -> x*2

Consumer<T>

accept(T t)

Consumes input

x -> System.out.println(x)

Supplier<T>

get()

Produces value

() -> Math.random()

8.3 Streams API and Operations

8.3.1 Explanation

The Streams API is a core part of Java’s functional paradigm. It enables data pipelines — sequential or parallel flows that process collections declaratively.
Streams differ from Collections in that they do not store data; instead, they provide a view over data to perform transformations efficiently.

Streams can be:

  • Sequential: Operate in a single thread.

  • Parallel: Split data for concurrent execution on multiple cores.

     

Key operations:

  1. Intermediate Operations – return another stream (lazy evaluation). Examples: filter(), map(), sorted().
  2. Terminal Operations – produce a result or side-effect. Examples: forEach(), collect(), reduce().

Streams allow chaining of operations to build data pipelines that are efficient and concise. They rely on internal iteration, freeing developers from manual looping logic.

8.3.2 Code

import java.util.*;

import java.util.stream.*;

public class StreamDemo {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");

List<String> result = names.stream()

.filter(n -> n.length() > 3)

.map(String::toUpperCase)

.sorted()

.collect(Collectors.toList());

System.out.println("Processed Names: " + result);

int totalLength = names.stream()

.mapToInt(String::length)

.reduce(0, Integer::sum);

System.out.println("Total Character Count: " + totalLength);

}

}

8.3.3 Example

Output:

Processed Names: [ALICE, CHARLIE, DAVID]

Total Character Count: 23

Explanation:
The filter() operation keeps names longer than three characters, map() converts them to uppercase, and sorted() arranges them alphabetically.
The second stream demonstrates reduce() for aggregation — summing character lengths efficiently using functional syntax.

8.3.4 Use Cases

  • Data processing and analytics pipelines.

  • Filtering and transforming collections with minimal code.

  • Performing aggregation (sum, average, max) operations.

  • Building scalable, parallelized computations.

     

8.3.5 Relevant Table

Operation Type

Example

Description

Result

Intermediate

filter(x -> x>5)

Returns another stream

Lazy operation

Terminal

collect(Collectors.toList())

Produces final output

Eager operation

Parallel

stream().parallel()

Split data into threads

Concurrent execution

Reduction

reduce(0, Integer::sum)

Aggregates stream data

Single result

Module 8: Java Streams and Lambda Expressions Introduction to Functional Programming in Java

Top Tutorials

Logo
Computer Science

CNN in Deep Learning 2026

A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.

4 Modules12 Lessons161 Learners
Start Learning
Logo
Computer Science

Breaking The Limits: Scaling Databases with MySQL Partitioning

Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.

7 Modules11 Lessons74 Learners
Start Learning
Logo

ML in Action: Hands-On Guide to Deploying and Serving Models

Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.

4 Modules10 Lessons78 Learners
Start Learning
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2026 AlmaBetter