Function Converter Java Example
In last tutorial you saw how to use Java 8 function as method and in this tutorial we will create function as converter which will take one input Double and based on its value it will return String result. This could be useful if you want to write utility class which will work as adapter, you can create many function converter in your utility class which will accept object and will return same or different object:
- DoubleToStringFunction.java:
package com.javahonk; import java.util.function.Function; public class DoubleToStringFunction { static Function<Double, String> doubleToStringCall = new Function<Double, String>() { public String apply(Double value) { if (value == 5.0) { return "Value is 5"; }else { return "Value is not 5"; } } }; }
Test class:
- FunctionConverterJava:
package com.javahonk; public class FunctionConverterJava { public static void main(String[] args) { System.out.println(DoubleToStringFunction.doubleToStringCall.apply(5.0)); } }
Reference: