Java Functional Review
Filed in: Java
Java Functional Review
Here is a quick review of some of the basic functional Java concepts that are beyond the Basic Java 101. In this article it is assumed you have a reasonable grasp of Imperative Java programming and Generics.
Lambda
These are actions on Objects or Method References. They are also designed to be able to write quick anonymous functions without littering the code with lots of little helper functions ie:
List myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
This simple command shows how you can create a stream of a collection and apply actions in a sequence. Note the last action must be Terminal. Also when updating contents on a stream you should recall that it uses lazy initialization.
The lambda s -> s.startsWith(“c") is a functional lambda and could be a little function on its own passing in parameter s which represents 1 string of the Array, however it is easier to read if we in line this anonymous function into filter. The filter will then only apply the next methods if and only if they meet the predicate set out in the filter. The chaining here allows an action on each object so rather than passing each item through a method discarding the filters and then map and terminate we can do it all in one.
You should also notice that these are effectively idem-potent actions. By this I mean they can run on any element of the array and there is no dependency between items in the array. This is important because if I had a large array I could use parallelStream instead of stream. This effectively runs multiple threads splitting the array into chunks and re-assembling when done.
Following on from the functional idea notice filer takes a predicate and auto assigns the element on which you can then call methods on the Type of that Object such as startsWith(…). The Type of s here is inferred as its a Stream of a List [ String ] in fact as long as you comply with the predicate return value of Boolean you can create your own Predicates and slide them in at runtime.
Optional
Optional is a useful monad ( a simple functor that supports map flatMap and identity and allows functions to be pipelined together ) that allows the wrapping of Nulls in order to avoid the dreaded NPE which is the bane of most developers. Now you can wrap the risk. Useful methods of Optional are
get() // value must be there to make this call.
ifPresent(Consumer super T > consumer ) // if there is a value send to a consumer
orElse(T Other) // return the value otherwise return a default value
Simple example:
String fileName=getFileName().orElse("No file found”);
We either have the file name or we send back a string saying cant find file, no NPE in sight.
Types of Functional Interfaces
Function - one arg returns result
Consumer - One arg no result implies side-effect
Supplier - no Arg returns result
Predicate - one arg returns boolean
BiFunction - two args return Res
BinaryOperator - two arg returns result of all same type
Unary Operator - two args ret res, where one arg must be same as Return type.
A functional example
Recall runnable interface has a Functional Interface annotation
Runnable r = () -> System.out.println("Hello World!");
Thread th = new Thread(r);
th.start();
This means we can run it as a lambda and pass it straight to Thread.
Here is an example of using the Function Interface.
Function xyz = size -> new String[size];
xyz.apply(3);
Default Methods
Java has long had a strange approach to defining default behaviour. You generally define it in an abstract class, but now you can define default behaviour in an interface and have the behaviour contained.
public interface myInf {
public void more();
default void doXYZ(){ ; }
}
Now the interface has a default behaviour of doXYZ() which can effectively be used to apply defaulting behaviour
You call the method like this
myInf.super.doXYZ();
The question becomes is this a functional Interface? Firstly does it support the contract a single abstract method more() - the default method is not abstract so does not count. so yes this is a functional interface.
Streams
a stream is just an Iterator that chains actions together the actions are either intermediate in that they return another stream or terminal in that they return a value.
Look at this example
int sum = Arrays.stream(new int[] { 1,2,3,4,5 } )
.filter(i -> i > 2)
.map(i -> i*2)
.min().orElse(0);
We create an array and make a stream chain together filter and map and given that min() returns an Optional we return the value orElse we return 0.
You should also note all streams are lazy that they only apply once there is a terminal value and only when they are needed. The terminal here is the min().
map and flatMap differences
Both the map and flatMap will apply the functional interface to the elements of the stream but flatMap will first flatten the the elements before applying the function.
This example shows how to use flatMap to only get the even number of each tuple
Integer[][] data = {{1,2},{3,4},{5,6}};
Arrays.stream(data).flatMap(row -> Arrays.stream(row)).filter(num -> num%2 == 0).
forEach(System.out::println);
Java DateTime Api
Based on Joda time and it is thread safe.
Probably best to do this via set of examples
LocalDateTime now = LocalDateTime.now();
// create date time as of right now
LocalDateTime date2016 = LocalDateTime.of(2016, Month.MARCH, 2, 13,59,59);
//create date march 2 2016 at 13:59:59
LocalDateTime now2 = LocalDateTime.of(LocalDate.now(), LocalTime.now());
//Create date using a LocalDate and a LocalTime obj
The important thing to remember is once you have created the LocalDateTime that is it it is fixed and immutable to change it you need to create a new object with the change applied. ie: to add 3 weeks you would create a new object with the change required ie:
LocalDateTime plus3weeks = now.plusWeeks(3);
Your local now variable is untouched recall it is immutable so thread safe, therefore all that happens is the method does the compute over the immutable and returns the new value.
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
Java
python
Scala
Investment Banking tutorials
HOME

Here is a quick review of some of the basic functional Java concepts that are beyond the Basic Java 101. In this article it is assumed you have a reasonable grasp of Imperative Java programming and Generics.
Lambda
These are actions on Objects or Method References. They are also designed to be able to write quick anonymous functions without littering the code with lots of little helper functions ie:
List
Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
This simple command shows how you can create a stream of a collection and apply actions in a sequence. Note the last action must be Terminal. Also when updating contents on a stream you should recall that it uses lazy initialization.
The lambda s -> s.startsWith(“c") is a functional lambda and could be a little function on its own passing in parameter s which represents 1 string of the Array, however it is easier to read if we in line this anonymous function into filter. The filter will then only apply the next methods if and only if they meet the predicate set out in the filter. The chaining here allows an action on each object so rather than passing each item through a method discarding the filters and then map and terminate we can do it all in one.
You should also notice that these are effectively idem-potent actions. By this I mean they can run on any element of the array and there is no dependency between items in the array. This is important because if I had a large array I could use parallelStream instead of stream. This effectively runs multiple threads splitting the array into chunks and re-assembling when done.
Following on from the functional idea notice filer takes a predicate and auto assigns the element on which you can then call methods on the Type of that Object such as startsWith(…). The Type of s here is inferred as its a Stream of a List [ String ] in fact as long as you comply with the predicate return value of Boolean you can create your own Predicates and slide them in at runtime.
Optional
Optional is a useful monad ( a simple functor that supports map flatMap and identity and allows functions to be pipelined together ) that allows the wrapping of Nulls in order to avoid the dreaded NPE which is the bane of most developers. Now you can wrap the risk. Useful methods of Optional are
get() // value must be there to make this call.
ifPresent(Consumer super T > consumer ) // if there is a value send to a consumer
orElse(T Other) // return the value otherwise return a default value
Simple example:
String fileName=getFileName().orElse("No file found”);
We either have the file name or we send back a string saying cant find file, no NPE in sight.
Types of Functional Interfaces
Function - one arg returns result
Consumer - One arg no result implies side-effect
Supplier - no Arg returns result
Predicate - one arg returns boolean
BiFunction - two args return Res
BinaryOperator - two arg returns result of all same type
Unary Operator - two args ret res, where one arg must be same as Return type.
A functional example
Recall runnable interface has a Functional Interface annotation
Runnable r = () -> System.out.println("Hello World!");
Thread th = new Thread(r);
th.start();
This means we can run it as a lambda and pass it straight to Thread.
Here is an example of using the Function Interface.
Function
xyz.apply(3);
Default Methods
Java has long had a strange approach to defining default behaviour. You generally define it in an abstract class, but now you can define default behaviour in an interface and have the behaviour contained.
public interface myInf {
public void more();
default void doXYZ(){ ; }
}
Now the interface has a default behaviour of doXYZ() which can effectively be used to apply defaulting behaviour
You call the method like this
myInf.super.doXYZ();
The question becomes is this a functional Interface? Firstly does it support the contract a single abstract method more() - the default method is not abstract so does not count. so yes this is a functional interface.
Streams
a stream is just an Iterator that chains actions together the actions are either intermediate in that they return another stream or terminal in that they return a value.
Look at this example
int sum = Arrays.stream(new int[] { 1,2,3,4,5 } )
.filter(i -> i > 2)
.map(i -> i*2)
.min().orElse(0);
We create an array and make a stream chain together filter and map and given that min() returns an Optional we return the value orElse we return 0.
You should also note all streams are lazy that they only apply once there is a terminal value and only when they are needed. The terminal here is the min().
map and flatMap differences
Both the map and flatMap will apply the functional interface to the elements of the stream but flatMap will first flatten the the elements before applying the function.
This example shows how to use flatMap to only get the even number of each tuple
Integer[][] data = {{1,2},{3,4},{5,6}};
Arrays.stream(data).flatMap(row -> Arrays.stream(row)).filter(num -> num%2 == 0).
forEach(System.out::println);
Java DateTime Api
Based on Joda time and it is thread safe.
Probably best to do this via set of examples
LocalDateTime now = LocalDateTime.now();
// create date time as of right now
LocalDateTime date2016 = LocalDateTime.of(2016, Month.MARCH, 2, 13,59,59);
//create date march 2 2016 at 13:59:59
LocalDateTime now2 = LocalDateTime.of(LocalDate.now(), LocalTime.now());
//Create date using a LocalDate and a LocalTime obj
The important thing to remember is once you have created the LocalDateTime that is it it is fixed and immutable to change it you need to create a new object with the change applied. ie: to add 3 weeks you would create a new object with the change required ie:
LocalDateTime plus3weeks = now.plusWeeks(3);
Your local now variable is untouched recall it is immutable so thread safe, therefore all that happens is the method does the compute over the immutable and returns the new value.
People who enjoyed this article also enjoyed the following:
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
And the following Trails:
C++Java
python
Scala
Investment Banking tutorials
HOME
