/home/wpollock1/public_html/Java/FunctionDemo.java
// Java function demo. This program defines a "lambda" function
// (not a method), stores it in a variable, and later executes it. The
// actual task done by this program is trivial: print a line of 'X', where
// the sole command line argument is the desired length of the line.
//
// Written 11/2016 by Wayne Pollock, Tampa Florida USA
// Import the package containing the Java standard functional Interfaces:
import java.util.function.*;
public class FunctionDemo
{
public static void main ( String [] args ) {
int length = 0;
// Convert first command line argument to an int:
try {
length = Integer.parseInt( args[0] );
} catch ( Exception e ) {
errorExit();
}
// Make sure the length is not negative:
if ( length < 0 )
errorExit();
// Define function (lambda) that returns a String of 'X' of length num:
Function<Integer, String> f = (num) -> {
StringBuilder result= new StringBuilder(num);
for ( int i=0; i <num; ++i) result.append("X");
return result.toString();
};
// Execute the function stored in variable f:
System.out.println( f.apply(length) );
}
private static void errorExit () {
System.err.println( "Usage: java FunctionDemo <num>" );
System.err.println( " Display a string of length num"
+ " composed of 'X'" );
System.exit(1);
}
}