Exploring the power of Functional Programming in Java

Table of Contents
Functional programming in Java, representational image.

Java Functional programming is a paradigm in programming that serves methods and functions like a variable, similar to functions in mathematics. It provides immutability that reduces the side effects and makes the code more concise and readable. It brings a new perspective to software development as it promotes pure functions (A pure function takes an input that generates some input that depends on its input like in mathematics), high-order functions, and a declarative programming approach.

In today’s world, programming and software development has reached such an extent that it serves multiple cutting-edge technologies. Still, we start our coding journey from the imperative programming paradigm rather than declarative.

In this blog, we will delve into the realm of functional programming in Java, exploring its paradigm, comparing it with traditional object-oriented concepts, uncovering its essential features, and requirements, and understanding why it has emerged as a prominent player in the dynamic technological landscape.

Evolution of Java Functional Programming

Let’s know why mathematics and lambda are important in programming. In the 1930s, a mathematician named Alonzo Churched developed a method for calculation as a function abstraction.

Lambda calculus comes with the greatest impact in programming majorly in functional programming languages. Or we can say, the functional programming paradigm implements lambda calculus.

Moreover, lambdas focuses on composition, on the other hand, functional programming provides a way to express those composition functions in software development.

Need for Functional Programming in Java

In functional programming, it provides a powerful composition technique where we don’t need to call a function with all its arguments.

Let’s see the difference between, how programming was before functional programming and the programming after Java 8 and functional programming was added into Java as one of its features:

Programming before Functional Programming

Imperative Programming

It checks the control flow and logic of the programming and focuses on describing how a program operates by giving a series of commands to the computer to perform and give a specific result.

Procedural and object-oriented programming languages are examples of imperative programming such as C, C++, Java, Python, etc.

Declarative Programming

Declarative programming specifies the expected result without checking the core logic and control flow of the program. The compiler makes the major decisions on how a code works rather than a programmer checking how code works in imperative programming.

Functional programming in Java is one of the major declarative programming languages such as SQL, LISP, Scala, Java 8, etc.

So, functional programming solves problems in software development such as managing complexity, increasing code readability, and maintaining consistent results. Its principles are becoming increasingly important in today’s business, and many languages, even languages ​​traditionally associated with importance or content orientation, have incorporated aspects of business.

Is Java declarative or object-oriented?

Java is primarily a most famous object-oriented programming language and follows the principles of the OOP concept. It is still an imperative programming language that follows an object-oriented paradigm, not a declarative.

Yes, it’s good to say Java adapts declarative features rather than Java, a declarative language.

Java with declarative Features

Java does have declarative features with the introduction of Java 8 and the inclusion of Stream API’s and other features.

Some Java 8 features that support Java in becoming more functional and declarative.:- 

  • Lambda Expressions
  • Functional Interface
  • Method Reference
  • Streams
  • Comparable and Comparator
  • Optional Class
  • Date and Time API

For more information, you can check the documentation.

So, Java 8 supports a more functional and declarative fashion of programming such that developers can impose these new features to make their code more concise and readable.

Important: It’s important to make clear that Java 8 features don’t change the fundamental nature of object-oriented. It is still object-oriented programming but yes, it provides a functional and declarative paradigm.

Understanding Functional programming via code

  1. Let’s take an example to find the sum of all elements in a list and print it.

Imperative Approach (Method before Java 8):

				
					import java.util.List;
import java.util.ArrayList;
public class MainSum {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(2);
		list.add(4);
		list.add(3);
		list.add(5);
		// To sum we use for each loop or can use Iterator
		int sum = 0;
		for (Integer a : list)
			sum += a;
		// printing the sum
		System.out.println("Sum of elements in the list: " + sum);
	}
}

				
			

Declarative Approach (Using Java 8):

				
					import java.util.List;
import java.util.ArrayList;
public class MainSum2 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(2);
		list.add(4);
		list.add(3);
		list.add(5);
		// To sum we use for each loop or can use Iterator
		int sum =list.stream().reduce(0, Integer::sum);
		
		System.out.println("Sum of elements in the list: " + sum);
	}
}

				
			

Let’s take another example:

We have given a list of strings and our task is to add all the strings in another list having the character “y” at the last index of a string and print that list.

Imperative:  Generally we use this approach while coding.

				
					import java.util.List;
import java.util.ArrayList;
public class StringEndWithChar {
	public static void main(String[] args) {
		List<String> list=new ArrayList<>();
		list.add("Ram");
		list.add("Deploy");
		list.add("Vivek");
		list.add("Carry");
		
		List<String> ans=new ArrayList<>();
		for(String s:list)
		{
			if(s.endsWith("y"))
				ans.add(s);
		}
		System.out.println("List contains 'y' at Last index: "+ans);
	}
}
Output: List contains 'y' at Last index: [Deploy, Carry]
				
			

Declarative Approach:

				
					import java.util.stream.Collectors;
import java.util.ArrayList;
public class StringEndWithChar2 {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("Ram");
		list.add("Deploy");
		list.add("Vivek");
		list.add("Carry");
		List<String> ans = list.stream().filter(s -> s.endsWith("y")).collect(Collectors.toList());
		System.out.println("List contains 'y' at Last index: " + ans);
	}
}
output:List contains 'y' at Last index: [Deploy, Carry]
				
			

From above examples, we have seen goals for both imperative and declarative approach in both example are same, so using declarative approach which makes code more readable , concise , memory optimised on the other hand in imperative approach the same task take a more memory and complex.

Benefits of Functional Programming

  • Improved Readability and Maintainability
  • Immutability
  • Pure Functions
  • Concurrency and Parallelism
  • High-Order Functions
  • Better Support for asynchronous programming
  • Compatibility with the modern paradigm
  • Learning a new perspective
  • Industry Trends

Conclusion

As we examine the work in Java 8, we delved into its evolution, its necessity, and the important role it plays in modern software development. The journey from basic programming to declarative programming helps improve code quality and readability.

As we see from the examples, functional programming provides many benefits, from improving code readability to providing concurrency and parallelism. 

In summary, the adaptation of functional programming in Java represents a major step towards efficiency and flexibility. By leveraging these features, developers can tackle the complexity of today’s development and unlock the full potential of Java.

In the upcoming blogs, we will come up with more concepts and features of functional programming, diving deeper, and further illuminating the code quality and productivity.

Stay tuned for more such content and practical components of Java’s functional programming components.

Share this blog

What do you think?

Contact Us Today for
Inquiries & Assistance

We are happy to answer your queries, propose solution to your technology requirements & help your organization navigate its next.
Your benefits:
What happens next?
1
We’ll promptly review your inquiry and respond
2
Our team will guide you through solutions
3

We will share you the proposal & kick off post your approval

Schedule a Free Consultation

Related articles