Files
second-brain/Clippings/Java Must Know Functional Programming Features.md

6.1 KiB
Raw Permalink Blame History

title, source, author, published, created, description, tags
title source author published created description tags
Java : Must Know Functional Programming Features https://skilledcoder.medium.com/java-must-know-functional-programming-features-088980534cb4
Skilled Coder
2024-09-13 2024-10-29 Functional programming brings clarity and efficiency to Java applications. In this guide, well explore ten strong functional programming features available in Java, explained in simple language with…
clippings

Ways to Make Java Functionally Fun

[

Skilled Coder

](https://skilledcoder.medium.com/?source=post_page---byline--088980534cb4--------------------------------)

Functional programming brings clarity and efficiency to Java applications. In this guide, well explore ten strong functional programming features available in Java, explained in simple language with practical code examples to help you improve your coding skills.

Lambda Expressions

Lambda expressions enable you to treat functionality as method arguments or code as data. They provide a clear and concise way to implement single-method interfaces (functional interfaces) using an expression.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");names.forEach(name -> System.out.println(name));

The lambda expression name -> System.out.println(name) passes each element of the list names to the printlnmethod.

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method. They can be implemented using lambda expressions, method references, or anonymous classes.

@FunctionalInterfaceinterface Greeting {    void sayHello(String name);}public class FunctionalInterfaceExample {    public static void main(String[] args) {        Greeting greeting = (name) -> System.out.println("Hello, " + name);        greeting.sayHello("World");    }}

The Greeting interface is a functional interface. We implement it using a lambda expression.

Stream API

The Stream API provides a functional approach to processing sequences of elements. It supports operations like map, filter, reduce, collect, and allows for parallel execution.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);List<Integer> squares = numbers.stream()    .map(n -> n * n)    .collect(Collectors.toList());System.out.println(squares); 

We use map to apply a function to each element and collect to gather the results into a list.

Method References

Method references provide a way to refer to methods without invoking them. They can be used in place of lambda expressions.

List<String> messages = Arrays.asList("Hello", "Functional", "Programming");messages.forEach(System.out::println);

System.out::println is a method reference to the println method, used here as a consumer in forEach.

Optional Class

Optional is a container object used to contain not-null objects. It helps in avoiding NullPointerException and provides methods for functional-style operations.

Optional<String> optionalName = Optional.ofNullable(getName());optionalName.ifPresent(name -> System.out.println("Name is: " + name));

ifPresent takes a consumer that is executed if the value is present.

Higher-Order Functions

Functions that take other functions as arguments or return functions are called higher-order functions.

public static void main(String[] args) {    Function<Integer, Integer> multiplyByTwo = createMultiplier(2);    System.out.println(multiplyByTwo.apply(5)); }public static Function<Integer, Integer> createMultiplier(int factor) {    return x -> x * factor;}

createMultiplier returns a function that multiplies its input by a given factor.

Functional Composition

Functional composition involves combining functions to build more complex functions.

Function<Integer, Integer> multiplyByTwo = x -> x * 2;Function<Integer, Integer> addThree = x -> x + 3;Function<Integer, Integer> composedFunction = multiplyByTwo.andThen(addThree);System.out.println(composedFunction.apply(5)); // Output: 13

andThen composes two functions; it first applies multiplyByTwo and then addThree.

Currying and Partial Application

Currying transforms a function with multiple arguments into a sequence of functions each with a single argument. While Java doesnt natively support currying, it can be simulated.

public static void main(String[] args) {    Function<Integer, Function<Integer, Integer>> add = x -> y -> x + y;    Function<Integer, Integer> addFive = add.apply(5);    System.out.println(addFive.apply(10)); }

add is a curried function that returns a function when applied with an argument.

Lazy Evaluation with Suppliers

Lazy evaluation delays the computation until the value is needed. In Java, this can be achieved using Supplier.

public static void main(String[] args) {    Supplier<Double> lazyValue = () -> computeValue();        System.out.println(lazyValue.get()); }public static double computeValue() {    System.out.println("Computing...");    return Math.random();}

The computeValue method is not called until lazyValue.get() is invoked.

Immutable Data Structures

Java provides unmodifiable collections that help in writing functional programs by ensuring data immutability.

List<String> list = List.of("A", "B", "C"); list.add("D"); 

List.of creates an immutable list; attempting to modify it results in an exception.

These features illustrate how Java incorporates functional programming concepts. You can write Java programs that benefit from the advantages of functional programming, such as improved modularity, easier concurrency, and reduced side effects.

On my Twitter and Instagram accounts, I frequently share my programming journey and development experiences.

Follow and subscribe to emails for unique coding articles.

Keep exploring, keep learning, and keep coding!

Thanks for reading :)