FunctionDemo.java

Download FunctionDemo.java

 1: // Java function demo.  This program defines a "lambda" function
 2: // (not a method), stores it in a variable, and later executes it.  The
 3: // actual task done by this program is trivial: print a line of 'X', where
 4: // the sole command line argument is the desired length of the line.
 5: //
 6: // Written 11/2016 by Wayne Pollock, Tampa Florida USA
 7: 
 8: // Import the package containing the Java standard functional Interfaces:
 9: import java.util.function.*;
10: 
11: public class FunctionDemo
12: {
13:     public static void main ( String [] args ) {
14:         int length = 0;
15: 
16:         // Convert first command line argument to an int:
17:         try {
18:             length = Integer.parseInt( args[0] );
19:         } catch ( Exception e ) {
20:             errorExit();
21:         }
22: 
23:         // Make sure the length is not negative:
24:         if ( length < 0 )
25:             errorExit();
26: 
27:         // Define function (lambda) that returns a String of 'X' of length num:
28:         Function<Integer, String> f = (num) -> {
29:             StringBuilder result= new StringBuilder(num);
30:             for ( int i=0; i <num; ++i) result.append("X");
31:             return result.toString();
32:         };
33: 
34:         // Execute the function stored in variable f:
35:         System.out.println( f.apply(length) );
36:     }
37: 
38:     private static void errorExit () {
39:         System.err.println( "Usage: java FunctionDemo <num>" );
40:         System.err.println( "       Display a string of length num"
41:             + " composed of 'X'" );
42:         System.exit(1);
43:     }
44: }