Since the beginning of the Java programming language, the OOP principle has been used. In OOP, we work with classes and objects. In Functional Programming, we work with functions. From Java 8, we got new features that allow us to practice Functional Programming. We got introduced to Functional Features such as:
Advantages of Functional Programming in Java
Functional programming in Java supports creating immutable objects, which can improve the stability of Java programs since mutable objects can cause many issues in Java applications, especially with multi-threaded environments. We can write more concise and readable code.
In Functional Programming, we can use functions/methods as first-class citizens. This means that Java will let us assign a function/method to a variable and pass it around like method parameters.
Another advantage is that we can tell our program what to do rather than how to do it.
Functional Programming code is concise and simple, an abstraction that hides the complexity and provides us with a clean interface to work with. When you apply a Functional Programming style in Java, you will come across concepts such as pure functions and lambda expressions.
The pure function always returns the same result for the same argument values, and has no side effects like modifying an argument or outputting something.
Lambda expression is an anonymous method, which means it can be created without belonging to any class. It can be passed around as an object and executed upon request. We will work a lot with lambda expressions in upcoming lessons. Example of the code written in a functional style:
Function<String, String> modifyString = (name) -> name.toUppecCase().concat("modified");
As you can see, we have a completely new syntax here, which you probably haven’t seen before. But don’t worry, we’ll cover everything in the upcoming lessons.
Let’s take a quick look at what’s going on here.
First, we have a Function interface that accepts two types, as we saw in Maps. The first type is for input and the second is for output. On the right side of the = sign, inside the parentheses, we have the input. We take that input and perform some operations.
First, we convert the string to uppercase, and we add the string to it. All that logic will be held by the modifyString variable. We can use that variable further in the program as every other variable in Java, which means that now we can pass a function as a method parameter.
With all these new features, we can write the program in a Declarative way rather than an Imperative.
Now, it’s time to start with the Function Programming tutorials.