Post

Functional programming in Java - What and Why?

This blog aims to define what functional programming is and few very basic examples of the same. **Note: I will be posting another blog with in detail examples for functional programming in Java.**

In Java, we write lots of code to perform certain operations with each line representing a sub operation. This style is called imperative programming. Since Java 8, this has been simplified a bit further by introducing functional programming which aims to build the code as functions and apply arguments to it. This makes the code less complex, cleaner, maintainable, and easier to test.

Below are some examples of code snippets we may or may not have encountered in code which has the concept of functional programming.

Iterating a list

The imperative way

Use case: Loop through a list and print its values. In the imperative world, a for statement would be used for the same like below and iterate each item.
1
2
3
for(int i = 0; i < listOfNames.size(); i++) {                      
    logger.debug(listOfNames.get(i)); 
}

The functional way

Replace for loop statement with forEach() to use the functional way and this reduces the code to one line.
1
listOfNames.forEach((name) -> logger.debug(name));

Transforming a list

The imperative way

Use case: Transforming through a list of names to contain all upper case names. In the imperative world, we would just use a for statement, iterate and add the upper case name to the newly created list.
1
2
3
4
List<String> uppercaseNames = new ArrayList<String>();
for(String name : listOfNames) { 
   listOfNames.add(name.toUpperCase()); 
}

The functional way

Replace with map() to perform this use case in the functional way.
1
2
3
List<String> uppercaseNames = listOfNames.stream() 
   .map(name -> name.toUpperCase()) 
   .collect(Collectors.toList());

Finding elements in a collection

The imperative way

Use case: Find list of names that contains all names that starts with A. In the imperative world, you would just use a for statement and check if each item starts with letter A.
1
2
3
4
5
6
List<String> startsWithA = new ArrayList<String>(); 
for(String name : listOfNames) {
   if(name.startsWith("A")) { 
         startsWithA.add(name); 
   }
}

The functional way

Replace using for loop statements with filter() to perform this use case in the functional way in the below fashion.
1
2
3
4
List<String> startsWithA =
   listOfNames.stream()
      .filter(name -> name.startsWith("A")) 
      .collect(Collectors.toList());

Upcoming blog - Part 2

Below blogs have in detailed examples for usages of functional programming in Java.
  1. Functional Interfaces examples (Functional programming)
  2. Monads examples (Functional programming)


This post is licensed under CC BY 4.0 by the author.