Java · · 9 min read

Functional Programming in Java, Explained

Functional Programming in Java, Explained

The code in the snippet above is an example of functional programming paradigm implementation in Java, which will filter and transform the List<String> in the request to another List<String>.

In this article, I will write about how to write code using Java’s API for functional programming. In the end, we will write our own stream API so we can understand how to implement a functional programming style in Java.

Functional Programming in Java

Functional programming in Java has been around for a long time. When Oracle released Java 8 back in 2014, they introduced lambda expression, which was the core feature for functional programming in Java.

Let’s see an example of the difference between using a sequence of imperative statements and using a functional style in Java.

      List<String> stringList = Arrays.asList("Hello", "World", "How", "Are", "You", "Today");

        // imperative declaration
        List<String> filteredList = new ArrayList<>();

        for (String string: stringList) {
            if (string.equals("Hello") || string.equals("Are")) {
                filteredList.add(string);
            }
        }

        List<String> mappedList = new ArrayList<>();
        for (String string: filteredList) {
            mappedList.add(string + " String");
        }

        for (String string: mappedList) {
            System.out.println(string);
        }

Imperative Style


        List<String> stringList = Arrays.asList("Hello", "World", "How", "Are", "You", "Today");

        //functional style
        stringList.stream()
                .filter(s -> s.equals("Hello") || s.equals("Are"))
                .map(s -> s + " String")
                .forEach(System.out::println);

Functional Style

As we can see, even though both pieces of code achieve the same result, the difference is significant. The imperative declaration code has many curly braces and is much longer, which makes it harder to read, compared to the functional style code.

Read next