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
andg: B->C
, composition is defined as the function h such thath(a) == g(f(a))
for eacha
. -
- Parameters:
g
- the second function to applyf
- the first function to apply- Returns:
- the composition of
f
andg
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
No comments:
Post a Comment