Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. // Demonstrate a method reference for a static method.
  2. // A functional interface for string operations.
  3. interface StringFunc {
  4.     String func(String n);
  5. }
  6. // This class defines a static method called strReverse().
  7. class MyStringOps {
  8.     // A static method that reverses a string.
  9.     static String strReverse(String str) {
  10.         String result = "";
  11.         int i;
  12.         for(i = str.length()-1; i >= 0; i--) {
  13.             result += str.charAt(i);
  14.         }
  15.         return result;
  16.     }
  17. }
  18. class MethodRefDemo {
  19.     // This method has a functional interface as the type of
  20.     // its first parameter. Thus, it can be passed any instance
  21.     // of that interface, including a method reference.
  22.     static String stringOp(StringFunc sf, String s) {
  23.         return sf.func(s);
  24.     }
  25.     public static void main(String args[])
  26.     {
  27.         String inStr = "Lambdas add power to Java";
  28.         String outStr;
  29.         // Here, a method reference to strReverse is passed to stringOp().
  30.         outStr = stringOp(MyStringOps::strReverse, inStr);
  31.         System.out.println("Original string: " + inStr);
  32.         System.out.println("String reversed: " + outStr);
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement