Advertisement
NLinker

Function vs method

Jun 29th, 2018
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. class MethodVsLambdas {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         // I. As a method
  6.         System.out.println(greeting(0, "Ivan"));
  7.         System.out.println(greetingF(0).apply("Ivan"));
  8.         // sum: 1 pts to method
  9.  
  10.         // II. As a function
  11.         Function<String, String> f = s -> greeting(0, s); // unwanted extra code
  12.         System.out.println(f.andThen(s -> "Greeting: " + s).apply("Ivan"));
  13.         System.out.println(greetingF(0).andThen(s -> "Greeting: " + s).apply("Ivan"));
  14.         // sum: 1 pts to function
  15.  
  16.         // III. As an argument
  17.         sendMessage(() -> greeting(0, "Ivan"));
  18.         // sendMessage(greetingF()); // fail! function can't be casted to supplier (or another
  19.         // functional interface).
  20.         // sum: -1 pts to function
  21.  
  22.         // IIII. Closures
  23.         List<Function<String, String>> functions = IntStream
  24.             .range(0, 10)
  25.             .mapToObj(MethodVsLambdas::greetingF)
  26.             .collect(Collectors.toList());
  27.         int n = functions.size();
  28.  
  29.         Random r = new Random(100);
  30.         for (int i = 0; i < 1000000; i++) {
  31.             // now you don't have the access to the original integer, the function is closed over it
  32.             // the call doesn't require the function to be created again
  33.             String result = functions.get(r.nextInt(n)).apply("iteration_" + i);
  34.             if (i % 10000 == 0) {
  35.                 System.out.println("result = " + result);
  36.             }
  37.         }
  38.         // So:
  39.         // function is created only once per single integer
  40.         // it is immutable and the integer is fixed forever inside it
  41.         // the call site doesn't require to pass the integer
  42.         // the call site doesn't consume additional construction for the function
  43.         // function: +4
  44.  
  45.         // grand sum: method   - 1 pts
  46.         //            function - 0 pts
  47.     }
  48.  
  49.  
  50.     static String greeting(int i, String name) {
  51.         return "Hi, " + name + ": " + i;
  52.     }
  53.  
  54.     static Function<String, String> greetingF(int i) {
  55.         return name -> "Hi, " + name + ": " + i;
  56.     }
  57.  
  58.     static <T> void sendMessage(Supplier<T> messageF) {
  59.         System.out.println(messageF.get());
  60.     }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement