Search This Blog

Tuesday 20 October 2015

The BiVersions of Java FunctionalInterfaces

In the previous post, we saw a version of the Function class that took two parameters into apply instead of one. Similar to the BiFunction interface, we also have BiPredicate, BinaryOperator, and BiSupplier .
The BiPredicate Interface allows for a test on two arguments. Consider the example:
BiPredicate<Integer, String> isEqual = (no, str) -> (no + "").equals(str);
System.out.println("Is True ? " + isEqual.test(45, "45.06"));
This class now performs the test on the two passed input type, checking if the integer value and string value are same.
Next is the BinaryOperator class - this is the binary version of the UnaryOperator. The class is
a type of BiFunction and thus exposes the apply method for two input arguments, which it transforms into an output, and all the three are of same type.
I tried out the class:
BinaryOperator<String> appendOperator = (a1, a2) -> a1 + " " + a2;
System.out.println("Strings " + "Hi &" + " Robin " 
   + "on combining results in " 
   + appendOperator.apply("Hi", "Robin"));
The lambda expression results in the two strings being summed to give a new string.
There are also two static methods available here that provide for easy min max code between two aguments.
Comparator<Ticket> ticketComparator = Comparator.comparing(t -> t.toString());
BinaryOperator<Ticket> maxOperator = BinaryOperator.maxBy(ticketComparator);
BinaryOperator<Ticket> minOperator = BinaryOperator.minBy(ticketComparator);
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
System.out.println("T1 is " + t1 + " and T2 is "+ t2);
System.out.println("The max of two tickets is " + maxOperator.apply(t1, t2));
System.out.println("The min of two tickets is " + minOperator.apply(t1, t2));
The output of the code is as below:
T1 is T[1804094807] and T2 is T[951007336]
The max of two tickets is T[951007336]
The min of two tickets is T[1804094807]
Next is the BiConsumer class which is a binary version of the Consumer class we have seen earlier.
{
Map<Ticket, String> ticketMap = new HashMap<>();
BiConsumer<Ticket, String> mapAdder = (ticket, opName) -> {
   ticketMap.put(ticket, opName);
};
mapAdder.accept(t1, "This is for Entry");
mapAdder.accept(t2, "This is for Exit");
System.out.println("No of entries in map are " + ticketMap.size()); //returns 2
You dont have a BiSupplier class - you cant return more than one item in java.

No comments:

Post a Comment