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

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…

Coding Exercise, Episode 1

I have received the following exercise from an interviewer, he didn't give the name of the problem. Honestly, I have no idea how to solve this problem even I have tried to read it three times before. Since I used to be a person who always tells myself "I am not the one good at algorithms", but giving up something too soon which I feel that I didn't spend enough effort to overcome is not my way. Then, I have sticked on it for 24 hours.

According to the given image on the problem, I tried to get more clues by searching. Thanks to Google, I found a similar problem on Hackerrank (attached link below). My target here was trying my best to just understand the problem and was trying to solve it accordingly by the Editorial on Hackerrank. Due to this circumstance, it turns me to love solving algorithms from now on (laugh). Check it out!
Problem You are given a very organized square of size N (1-based index) and a list of S commands
The ith command will follow the format (a[…

Applying pipeline “tensorflow_embedding” of Rasa NLU

According to this nice article, there was a new pipeline released using a different approach from the standard one (spacy_sklearn). I wanted to give it a try to see whether it can help with improving bot’s accuracy.

After applying done, I gave an evaluation of “tensorflow_embedding”. It seemed to work better a bit. For example, I defined intents “greet” and “goodbye” with some following messages in my training data.
## intent:greet- Hey! How are you? - Hi! How can I help you? - Good to see you! - Nice to see you! - Hi - Hello - Hi there ## intent:goodbye- Bye - Bye Bye - See you later - Take care - Peace In order to play around with Rasa NLU, I created a project here. You can have a look at this change from this pull request. Yay!

When I entered message “hi bot”, then bot with “tensorflow_embedding” could detect intent “greet” with better confidence scores rather than bot with “spacy_sklearn”. The following are responses after executing curl -X POST localhost:5000/parse -d '{&qu…

Only allow input number value with autoNumeric.js

autoNumeric is a jQuery plugin that automatically formats currency and numbers as you type on form inputs. I used autoNumeric 1.9.21 for demo code.

1. Dowload autoNumeric.js file from
2. Import to project
<script src=""></script> <script type="text/javascript" src="js/autoNumeric.js"></script> 3. Define a function to use it
<script type="text/javascript"> /* only number is accepted */ function txtNumberOnly_Mask() { var inputOrgNumber = $("#numberTxt"); inputOrgNumber.each(function() { $(this).autoNumeric({ aSep : '', aDec: '.', vMin : '0.00' }); }); } </script>
4. Call the function by event
<form> <input type="text" value="" id="numberTxt"/>(only number) </form> <script type="te…

Attribute 'for' of label component with id xxxx is not defined

I got the warning in the log file when I have used the tag <h:outputLabel> without attribute "for" in xhtml file. It was really polluting my server log files.

The logged information actually makes sense anyway! We could find an answer as the following:

"Having h:outputLabel without a "for" attribute is meaningless. If you are not attaching the label, you should be using h:outputText instead of h:outputLabel."

However, these solutions are not possible just for my situation. Instead of using h:outputText for only displaying text, my team has used h:outputLabel too many places. We were nearly in our release time (next day) so it is quite risky and takes much efforts if we try to correct it. Because the style (with CSS) is already done with h:ouputLabel. The alternative by adding attribute "for" the existing h:outputLabel is not reasonable either. I really need to find another solution.
Fortunately, I came across a way if I change to use p:out…