functional-programming

Functional Programming

Pure functional programming follows these principles:

  • No internal state or side effects

  • Uses pure functions (same input → same output)

  • Emphasizes higher-order functions (functions that take or return other functions)

"Functional programming is about writing functions that take inputs and return outputs without changing anything outside the function — no modifying global variables, just working with the arguments passed in."

When to use functional programming paradigm?

Use functional programming when you want to write cleaner, more concise code that focuses on what to do rather than how to do it, especially for processing collections or streams.

Intermediate Operations (lazy)

These are lazy operations that return a new stream and are executed only when a terminal operation is invoked.

  • filter(Predicate) – Keeps elements that match a condition

  • map(Function) – Transforms each element

  • flatMap(Function) – Flattens nested structures (e.g., Stream of Lists)

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

        List<Integer> evensTimesTen = numbers.stream()
                .filter(n -> n % 2 == 0)    // intermediate: keep even numbers
                .map(n -> n * 10)           // intermediate: multiply each by 10
                .collect(Collectors.toList()); // terminal: trigger processing

        System.out.println(evensTimesTen); // Output: [20, 40, 60]

Terminal Operations (Eager)

These trigger the stream pipeline and produce a result or side effect.

  • collect(Collectors.toList()) – Collects the result into a list

  • forEach(Consumer) – Performs an action for each element

  • reduce(...) – Reduces all elements into a single result

Function

.andThen

.compose

.apply

Consumer

.accept

Can be used as a callback too!

Predicate

Returns a boolean

Supplier

Supplier is good because it lets you defer the creation of a value until it's actually needed, saving resources and improving efficiency.

"You want to define the logic now, but only execute it later, possibly under certain conditions."

Optionals

.isPresent

.orElseThrow

Some functions will return a Optional object which means something or nothing.

Or we can use Optional to avoid NullPointerException

Combinator pattern in functional programming

Last updated