Functional Programming in Java — Simple Explanation with Examples

 

Functional Programming in Java — Simple Explanation with Examples

Functional Programming (FP) is a programming style that focuses on what to compute rather than how to do it, by using functions, immutability, and declarative code.

Java supports functional programming features since Java 8, making it a hybrid language (Object-Oriented + Functional).


🧠 What Is Functional Programming?

In simple terms:

Functional programming means writing code using functions that do not change data, and instead return new results.

Key idea:

InputFunctionOutput

Same input always produces the same output.


🔑 Core Principles (Simple)

1️⃣ Pure Functions

  • Output depends only on input

  • No external state modification

int add(int a, int b) { return a + b; }

2️⃣ Immutability

  • Data is not modified after creation

List<Integer> list = List.of(1, 2, 3); // immutable

3️⃣ Declarative Style

Say what you want, not how to loop.

list.stream() .filter(x -> x > 10) .map(x -> x * 2) .toList();

4️⃣ Functions as Values

Functions can be:

  • passed as arguments

  • stored in variables

Runnable r = () -> System.out.println("Hello");

❓ Does Java Support Functional Programming?

✅ Yes (Since Java 8)

Java supports functional programming through:

  • Lambda expressions

  • Functional interfaces

  • Streams API

  • Method references

  • Optional

Java is not a pure functional language, but it encourages functional style.


🧩 Functional Programming Features in Java

🔹 Lambda Expressions

x -> x * 2

🔹 Functional Interfaces

Interface with one abstract method.

@FunctionalInterface interface Calculator { int add(int a, int b); }

🔹 Streams API

Process collections in a functional way.

List<Integer> nums = List.of(5, 10, 15); List<Integer> result = nums.stream() .filter(x -> x > 10) .map(x -> x * 2) .toList();

✔ Original list unchanged
✔ New list created


🔍 Does Stream Code Change State?

❌ No — it does not mutate the original data.

System.out.println(nums); // [5, 10, 15] System.out.println(result); // [30]

Only transformations occur, not mutation.


⚠️ Side Effects (Important Note)

This introduces side effects:

.forEach(System.out::println); // prints to console

Printing is not pure, but Java allows controlled side effects.


🏭 Real-World Example: Order Processing

Requirement

  • Get completed orders

  • Apply discount

  • Calculate total amount

double total = orders.stream() .filter(Order::isCompleted) .mapToDouble(o -> o.getPrice() * 0.9) .sum();

✔ Clear
✔ Readable
✔ Easy to parallelize


🧠 Why Functional Programming Is Useful

  • Less boilerplate code

  • Fewer bugs

  • Easy to test

  • Better concurrency support

  • Improved readability


❌ What Functional Programming Is NOT in Java

Java FP:

  • ❌ Is not purely functional

  • ❌ Allows mutable state

  • ❌ Allows side effects

But it promotes safer coding practices.


🆚 Imperative vs Functional (Quick View)

Imperative

for (int n : nums) { if (n > 10) { result.add(n * 2); } }

Functional

nums.stream() .filter(n -> n > 10) .map(n -> n * 2) .toList();

🎯 Interview-Ready Answer

Functional programming is a paradigm that emphasizes pure functions, immutability, and declarative code.
Java supports functional programming through lambdas, functional interfaces, and streams since Java 8.


📝 One-Line Summary

Functional programming in Java means transforming data using functions without changing the original state.

No comments:

Post a Comment

Java Design Patterns With What • Why • When • Full Java Programs • Client Usage

  Java Design Patterns  With What • Why • When • Full Java Programs • Client Usage Introduction Design Patterns are proven solutions to...

Featured Posts