Search This Blog

Wednesday, 7 October 2015

Variations in java functions

In the previous post, we saw the Function Interface that takes an object of one type and transforms it into an object of another type. Consider the user case where we need to split a string and retain only the second half.

public static void testSingleType() {
      String testInp = "Hello";
      Function<String, String> splitter = inp -> inp.substring(inp.length() / 2);
      System.out.println(splitter.apply(testInp));// will print 'llo'
   }
As seen here while we transformed the string content/value, we did not really transform from one type to another. The two type parameters here is kind of redundant. Java 8 has provided for this case by introducing the UnaryOperator class:
From the java docs:
Represents an operation on a single operand that produces a result of the
same type as its operand.  This is a specialization of Function for
the case where the operand and result are of the same type.
Accordingly the updated class is :
public static void testSingleType() {
      String testInp = "Hello";     
      UnaryOperator<String> unaryStyleSplitter = inp -> inp.substring(inp.length() / 2);
      System.out.println(unaryStyleSplitter.apply(testInp));// will print 'llo'
   }
There is also a three parameter version of Function - one that takes two parameters and transforms that to a singe output.
BiFunction<String, Character, Long> cleanNumber = (value, character) 
                     -> Long.valueOf(value.replaceAll(character+"", ""));
System.out.println(cleanNumber.apply("123#45#12", '#'));
//will print 1234512

1 comment: