Skip to main content

Java 8 - Using Functions as Values

The following is a series of posts about "functional programming in Java" which is the result of my understanding by reading the book "Java 8 in Action: Lambdas, Streams, and Functional-style Programming, by Alan Mycroft and Mario Fusco".
1. Why functional programming?
2. Functional programming in Java 8
3. Java 8 - Using Functions as Values
4. Java 8 - Persistent data structure

In general, the phrase "functional-style programming" means the behavior of functions should be like that of mathematical-style functions - no side effects.

In programmers' point of views, functions may be used like other values: passed as arguments, returned as result, and stored in data structures. That means we can use the :: operator to create a method reference, and lambda expressions to directly express function values. For example:
//method reference
Function<String, Integer> strToInt = Integer::parseInt;

//lambda expression
Comparator<Integer> comparator = (a, b) -> a.compareTo(b);

There are two practical techniques to apply in our codebase.

Higher-order functions

For example:
 Comparator<Apple> c = Comparator.comparing(Apple::getWeight);
Higher-order functions (like Comparator.comparing) that can do at least one of following:
  • Take one or more functions as parameter
  • Return a function as result
Foo: If so, for what? 
Bar: Good question! To compose functions to create a pipeline of operations. It's close to declarative programming.


A function of two arguments (x and y, say) is seen instead as a function g of one argument that returns a function also one argument. The value returned by the latter function is the same as the value of the original function, that is, f(x,y) = (g(x))(y).

Brain overload! For example, you want to convert Celsius to Fahrenheit, the formula is f(x) = x *9/5 + 32. Not only this case but we can see the basic pattern of all unit conversion is as follow:
static double converter(double x, double f, double b) {
 return x * f + b;
This method is a bit too general. Obviously, we can use it to apply for all unit conversion but it would be tedious and you might accidentally mistyped them. There is an better approach:
static DoubleUnaryOperator curriedConverter(double f, double b){
 return (double x) -> x * f + b;
Instead of passing all the arguments x, f and b all at once to the converter method, you only ask for the arguments f and b and return another function, which given an argument x return x*f + b.

Why is it the better approach? This enables you to reuse the convention logic and create different functions with different convention factors:
DoubleUnaryOperator convertCtoF = curriedConverter(9.0/5, 32);
DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);
DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0);
Instead of three different method for each conversion factor:
static double convertCtoF(double x, double f, double b) {
 return x * f + b;

static double convertUSDtoGBP(double x, double f, double b) {
 return x * f + b;

static double convertUSDtoGBP(double x, double f, double b) {
 return x * f + b;
Foo: If so, for what?
Bar: It helps you modularize functions and reuse code!


Image result for java 8 in action

[1]. Alan Mycroft and Mario Fusco, Java 8 in Action: Lambdas, Streams, and Functional-style Programming. Part 4. Beyond Java 8.


Post a Comment

Popular posts from this blog

My 2017 Review

Passion for System Design After finishing a one year project, my longest stable team (3 years) was separated into two smaller teams. Sadly, but that was a good chance for me to become a key member in my new team. My preferred skills is about system architectures; therefore most of the tasks of building the application structures are handled by me. In order to enhance my design system skills, I have spent much my time for reading books closely after work. These following books helps me a lot.
- Object-Oriented Thought Process | Matt Weisfeld
- Head First Design Pattern | Elisabeth Freeman and Kathy Sierra
- Java 8 in Action: Lambdas, Streams, and Functional-style Programming | Alan Mycroft and Mario Fusco
Junior Technical Architect I was requested to join a technical architect team (aka Team. Alpha) where I actually has gained experiences almost on interviewing candidates for my company (lol). Besides, I noticed myself must improve the skills of convincing people because I have had a …

AngularJS - Build a custom validation directive for using multiple emails in textarea

AngularJS already supports the built-in validation with text input with type email. Something simple likes the following:
<input name="input" ng-model="email.text" required="" type="email" /> <span class="error" ng-show="myForm.input.$"> Not valid email!</span>
However, I used a text area and I wanted to enter some email addresses that's saparated by a comma (,). I had a short research and it looked like AngualarJS has not supported this functionality so far. Therefore, I needed to build a custom directive that I could add my own validation functions. My validation was done only on client side, so I used the $validators object.

Note that, there is the $asyncValidators object which handles asynchronous validation, such as making an $http request to the backend.

This is just my implementation on my project. In order to understand that, I supposed you already had experiences with Angular…

Strategy Design Pattern

For example, I have an program with an Animal abstract class and two sub-classes Dog and Bird. I want to add a new behavior for the class Animal, this is "fly".  Now, I face to two approaches to solve this issue:

1. Adding an abstract method "fly" into the class Animal. Then, I force the sub-classes should be implemented this method, something like:

public abstract class Animal{ //bla bla public abstract void fly(); } public class Bird extends Animal{ //bla bla public void fly(){ System.out.println("Fly high"); } } public class Dog extends Animal{ //bla bla public void fly(){ System.out.println("Cant fly"); } }
2. Creating an interfaces with method "fly" inside. The same issue to abstract class, I force the classes these implement this interface should have a method "fly" inside:

public interface Flyable{ public void fly(); } public class Bird implements Flyable{ //bla bla public void fly(){ System.out.println…

How did I start practising BDD?

At the beginning days I have practised TDD (Test Driven Development) with using JUnit, I approached that I should test methods belong to a class. For example:

I have a class with some methods:

public class A{ public void method1(){ } public void method2(){ } }
And then, I wrote some test methods to check the corresponding ones, for example:

public class ATest{ @Test public void testMethod1(){ .... assertTrue(...); ..... assertEquals(...); } @Test public void testMethod2(){ } }
After that, I know that a test method (ex: testMethod1) should just only tests one thing, so I decided to write more methods for each cases. It looks like the following:

@Test public void testMethod1_When_Case1(){ .... assertTrue(...); } @Test public void testMethod1_When_Case2(){ .... assertEquals(...); }
However, it was not a really good approach because it seems that I just focused on test the functionality of the method of the class. With TDD approach, I knew that I should test the…

Styling Sort Icons Using Font Awesome for Primefaces' Data Table

So far, Primefaces has used image sprites for displaying the sort icons. This leads a problem if we want to make a different style for these icons; for example, I would make the icon "arrow up" more blurry at the first time table loading because I want to highlight the icon "arrow down". I found a way that I can replace these icons to Font Awesome icons.

We will use "CSS Pseudo-classes" to archive it. The hardest thing here is that we should handle displaying icons in different cases. There is a case both "arrow up" and "arrow down" showing and other case is only one of these icons is shown.

.ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s { background-image: none; margin-left: 5px; font-size: 1.1666em; position: relative; } .ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s:not(.ui-icon-triangle-1-s)::before { content: "\f106"; font-family: "FontAwesome"; position: absolute; t…