DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Redefining Java Object Equality
  • Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?

Trending

  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Creating a Web Project: Caching for Performance Optimization
  1. DZone
  2. Coding
  3. Java
  4. Functional Programming in Java 8 (Part 0): Motivation

Functional Programming in Java 8 (Part 0): Motivation

As we begin a series on functional programming, see why you should consider making the move and how you can incorporate it using some familiar Java.

By 
Niklas Wuensche user avatar
Niklas Wuensche
·
Jan. 24, 17 · Tutorial
Likes (79)
Comment
Save
Tweet
Share
32.6K Views

Join the DZone community and get the full member experience.

Join For Free

As I’ve seen in my previous post, the interest in functional programming is high. This is the reason I want to write an introduction about it.

I work a lot in Haskell and Java in my free time. The idea to combine both of these languages in Java was a dream come true. After this introduction, I hope you will feel the same.

What Is Functional Programming, Really?

You might have heard about functional programming (FP) and how great it is to reduce your LOC and enhance the readability of your code. But what does it really mean to program functional, and what are the main differences to OOP?

1. All Variables Are Final

Java
 
Lets look at this function to greet some users. First of, it is written OO.
 public String greet(List<String> names) {
    String greeting = "Welcome ";
    for(String name : names) {
        greeting += name + " "; // We don't care about the last space right now.
    }
    greeting += "!";
    return greeting;
}


This is a perfectly valid function to create such a great String in Java.

But if you are fP, this won’t work. You change the state of greeting, which is not allowed in fP. So, if you try to make the greeting final, you will get an error. Every time you use += with that String, you change its state.

What you basically do in fP is the concatenation of all names in one line into one String.

Java
 
public String greet(List<String> names) {
    final String reducedString = "Welcome " + names.get(0) + " " + names.get(1) + " " + ...
            + names.get(names.size()-1) + " ";
    return reducedString + "!";
}


If you think that this looks nasty, you’re right! But there is a fP function to make this nicer.

I will give you the right fP function here. Don’t worry if you don’t understand it now; we will talk about all of this in part 3.

Java
 
public String greet(List<String> names) {
    String greeting = names
            .stream()
            .map(name -> name + " ")
            .reduce("Welcome ",
                    (acc, name) -> acc + name);
    return greeting + "!";
}


The good thing about final variables is that their value is always the same. This makes debugging and testing so much easier!

2. Don’t Use Global Variables (And Forget About Side Effects)

I’ve chosen the example of a global time object. You write a static function, which returns the current time as a String. An OO function could look like this:

Java
 
public class Utils {

    private static Time time;

    public static String currTime() {
        return time.now().toString();
    }

}


If you use currTime twice, the result will be different because the time will be different. Although we had the same input (which is none), currTime had two different results!

This can’t happen in fP. Every method only depends on its parameters and on nothing else! So, if we want to do something like this, the Time object has to be a parameter of currTime:

Java
 
public class Utils {

    public static String currTime(Time time) {
        return time.now().toString();
    }

}


This might seem odd in the OO world, but it has some benefits.

On one hand, it is much easier to read the code. If you know that a method only relies on its parameter, you don’t have to look for global variables that do the magic in your method. On the other hand, testing is much easier, too! When you want to test the fP currTime method, you can mock the Time object. In the OO version, it’s really difficult to mock the static Time object.

3. Use Functions as Parameters

In fP, functions can be arguments of another function! How cool is that? Just think of a function which adds 1 to every number of a List<Integer>. How would you do that, OO? Here’s a snippet:

Java
 
public List<Integer> addOne(List<Integer> numbers) {
    List<Integer> plusOne = new LinkedList<>();

    for(Integer number : numbers) {
        plusOne.add(number + 1);
    }

    return plusOne;
}


Now, you have to handle two lists. This can be very confusing and leads to errors. There is also the chance to change the state of numbers. This could lead to problems in later parts of the program.

In fP, you can map a function with every element of a List. In this example, this means that you want to “map” number+1 to every item in the list and store this in a new List.

Don’t worry if you don’t understand all of it now; we will learn about this in part 3. The fP method would look like this:

Java
 
public List<Integer> addOne(List<Integer> numbers) {
    return numbers
            .stream()
            .map(number -> number + 1)
            .collect(Collectors.toList());
}


This reduces the number of variables and, therefore, the places where you can make errors. Here, you create a new list and leave numbers like it is.

Conclusion

I hope you can see the benefits of fP. Later on, you will learn to truly appreciate them. Final variables are a big help in terms of multi-threading. The lack of global variables improves the testability and functions as parameters improve the code quality.

And don’t worry. In the beginning, you can mix OOP and fP in your code.

In the next part, we will talk about functions as parameters. Therefore, I will introduce the anonymous function(lambdas) and method references.

I hope you liked this short introduction to the big topic of functional programming. Please write me when something’s not clear. Or is there any reason for you to hate functional programming at all? I would love to discuss these topics with you.

Functional programming Java (programming language) Strings

Published at DZone with permission of Niklas Wuensche, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Redefining Java Object Equality
  • Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!