Skip to content

Instantly share code, notes, and snippets.

@ayago
Created July 25, 2019 08:15
Show Gist options
  • Save ayago/7a6b61c93781e5eaa220be79c823dda5 to your computer and use it in GitHub Desktop.
Save ayago/7a6b61c93781e5eaa220be79c823dda5 to your computer and use it in GitHub Desktop.
Defining functions in Java
import java.util.function.Function;
import static java.lang.String.format;
class Scratch {
public static void main(String[] args) {
//instantiate as an object
Function<Integer, String> stringifyInteger = stringifyInteger();
System.out.println(format("Output is %s", stringifyInteger.apply(3)));
//lambda format
Function<Integer, String> stringifyIntegerLambda = a -> a.toString();
System.out.println(format("Output is %s", stringifyIntegerLambda.apply(3)));
//method reference
Function<Integer, String> stringifyIntegerMethodRef = Object::toString;
System.out.println(format("Output is %s", stringifyIntegerMethodRef.apply(3)));
}
private static Function<Integer, String> stringifyInteger(){
return new Function<Integer, String>() {
@Override
public String apply(Integer integer) {
return integer.toString();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment