Sunday, January 4, 2015

Google Gauva API in a one glance: Composite Function


Guava API provide a way to apply series of functions on the given collection using Functions.compose

public static <A,B,C> Function<A,C> compose(Function<B,C> g,
                                            Function<A,? extends B> f)
Returns the composition of two functions. For f: A->B and g: B->C, composition is defined as the function h such that h(a) == g(f(a)) for each a.
Parameters:
g - the second function to apply
f - the first function to apply
Returns:
the composition of f and g

to test it further please follow my blog entry and add one method to the GuavaFunctionDemo class and run it
/**
*
*/
package com.rajkrrsingh.test.guava;

import java.util.Collection;
import java.util.Iterator;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Collections2;

/**
* @author rks
* @04-Jan-2015
*/
public class GuavaFunctionDemo {

public static void main(String[] args) {
//printEmployeeInUpperCase();
printResultofCompositeFunction();
}

// Transformation of one collection to the other collection using Guava function
public static void printEmployeeInUpperCase(){
Collection<String> upperCaseEmpName = Collections2.transform(Employee.getEmployeeList(),new Function<Employee, String>() {

@Override
public String apply(Employee emp) {
if(emp != null)
return emp.getEmpName().toUpperCase();
return "";

}
});

Iterator<String> itr = upperCaseEmpName.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

// Apply a series of transformation by compostion of function
public static void printResultofCompositeFunction(){
Function<Employee, String> upperCaseEmpName = new Function<Employee, String>() {

@Override
public String apply(Employee emp) {
if(emp!=null)
return emp.getEmpName().toUpperCase();
return "";
}
};

Function<String, String> reverseEmpName = new Function<String, String>() {

@Override
public String apply(String empName) {
if (empName!=null) {
return new StringBuilder(empName).reverse().toString();
}
return "";
}

};
;
Collection<String> upperReverseCollection = Collections2.transform(Employee.getEmployeeList(), Functions.compose(reverseEmpName, upperCaseEmpName));

Iterator<String> itr = upperReverseCollection.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

}

you can see here we have applied two function here, the first on is to change element of the collection in uppercase and then reverse it.

Result:
SKR
KERED
KCAJ
KCIN




Post a Comment