Advertisement
haykart

Untitled

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