Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MethodVsLambdas {
- public static void main(String[] args) {
- // I. As a method
- System.out.println(greeting(0, "Ivan"));
- System.out.println(greetingF(0).apply("Ivan"));
- // sum: 1 pts to method
- // II. As a function
- Function<String, String> f = s -> greeting(0, s); // unwanted extra code
- System.out.println(f.andThen(s -> "Greeting: " + s).apply("Ivan"));
- System.out.println(greetingF(0).andThen(s -> "Greeting: " + s).apply("Ivan"));
- // sum: 1 pts to function
- // III. As an argument
- sendMessage(() -> greeting(0, "Ivan"));
- // sendMessage(greetingF()); // fail! function can't be casted to supplier (or another
- // functional interface).
- // sum: -1 pts to function
- // IIII. Closures
- List<Function<String, String>> functions = IntStream
- .range(0, 10)
- .mapToObj(MethodVsLambdas::greetingF)
- .collect(Collectors.toList());
- int n = functions.size();
- Random r = new Random(100);
- for (int i = 0; i < 1000000; i++) {
- // now you don't have the access to the original integer, the function is closed over it
- // the call doesn't require the function to be created again
- String result = functions.get(r.nextInt(n)).apply("iteration_" + i);
- if (i % 10000 == 0) {
- System.out.println("result = " + result);
- }
- }
- // So:
- // function is created only once per single integer
- // it is immutable and the integer is fixed forever inside it
- // the call site doesn't require to pass the integer
- // the call site doesn't consume additional construction for the function
- // function: +4
- // grand sum: method - 1 pts
- // function - 0 pts
- }
- static String greeting(int i, String name) {
- return "Hi, " + name + ": " + i;
- }
- static Function<String, String> greetingF(int i) {
- return name -> "Hi, " + name + ": " + i;
- }
- static <T> void sendMessage(Supplier<T> messageF) {
- System.out.println(messageF.get());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement