Created
July 25, 2019 08:15
-
-
Save ayago/7a6b61c93781e5eaa220be79c823dda5 to your computer and use it in GitHub Desktop.
Defining functions in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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