Commit 079a114f authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+24 −0
Changes for Functional Programming in Java 8 - Working Files/Chapter 1/aboutMe.txt: 24 added lines, 0 removed lines.
Original line number Diff line number Diff line

  -- The mercifully short story:

    # An academic by profession, but with lots of consulting experience as a programmer

      ## Full-time faculty member for 30-plus years in DePaul's College of Computing and Digital Media
         PhD from Northwestern University

      ## Long-term experience in programming production planning-scheduling systems (steel industry mostly) and
         product configuration systems (large-vehicle manufacturing mostly)

    # The hands-on approach is the hands-down best approach.

    # I've used Java since JDK 1.0 (whew!), and am really enthusiastic about the additions to core Java8.

    # Feel free to contact me at: kalin@cs.depaul.edu
                                  http://condor.depaul.edu/mkalin

    Here's hoping that you'll become an enthusiastic user of the functional-programming features
    introduced in Java8.

    Marty Kalin

+49 −0
Changes for Functional Programming in Java 8 - Working Files/Chapter 1/courseOverview.txt: 49 added lines, 0 removed lines.
Original line number Diff line number Diff line

 -- Functional programming in Java8 (and beyond)

  # Requirements: core Java 8 (Java SE 8) or greater -- that's it.

  # But why add new features to Java? Isn't there already enough on the Java table?

    ## The new 'functional programming' features squarely address modern needs:

       -- 'Big data': programs now work regularly with rich data sets that need processing.

       -- 'Multi-core machines': computing devices, of whatever size, are multi-processor machines
         
       -- Programming languages should make it easier to deal with big data that needs processing
          on multi-processor machines. 

          ### Java now does.

    ## How functional programming fits into a 'data pipeline' model of computing:
 
                   plug different functions in here    ...                 plug different functions in here
                               /                        /                                \
       rich data source---->filter1---->process1---->filter2---->process2---->...---->collect---->report---->....
              /                            /                        /                                /
       e.g., customer data     plug different functions in here     ...           plug different functions in here

  # The new features on the 'function' side:
 
    -- Anonymous functions ('lambdas'): the core new feature

    -- Method and constructor references: a cleaner, better way 

    -- Both of these 'functional' features work well with the new 'data streaming' constructs in Java.

  # The approach in this course:

    -- Full code examples, which can be compiled, run, and tweaked on your own system.
       ## Lots and lots and lots of code...

    -- How functional programming meets the needs of modern apps, and takes advantage of
       the machines these apps run on.

    -- Focus on the programming goals (e.g., terse and simple-to-modify code, run-time efficiency,
       thread-safety) that the 'functional style' promotes.

 
         
      
  
+52 −0
Changes for Functional Programming in Java 8 - Working Files/Chapter 2/CleanerCode.java: 52 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*
  Simple 'Swing set' app to illustrate just how much cleaner the new
  lambda syntax is. In this example, a lamdba serves as the 
  event-handling code for a button-clicked event.
 */
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

public class CleanerCode {
    public void initAndShow() {
	JFrame.setDefaultLookAndFeelDecorated(true);
	JFrame win = new JFrame();       
	win.setLayout(new FlowLayout());
	win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	JLabel currentTime = new JLabel(new Date().toString());
	Font font = new Font("Courier New", Font.BOLD, 14);
	currentTime.setFont(font);
	win.add(currentTime);           

	//## Here's what's of interest:
	JButton updateCurrentTime = new JButton("Update current time");
	updateCurrentTime.setFont(font);
	win.add(updateCurrentTime);

	//### old way
	/*
	// Compiler generates CleanerSyntax$1.class as the unnamed inner class...
	updateCurrentTime.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
		    currentTime.setText(new Date().toString());
		}
	    });
	*/
	//### new way (BTW, there's no CleanerSyntax$1.class generated)
	updateCurrentTime.addActionListener(e -> currentTime.setText(new Date().toString()));
	    
	win.setSize(300, 100);  
	win.setVisible(true);
    }
    
    public static void main(String args[ ]) {
	new CleanerCode().initAndShow();
    }
}
+63 −0
Changes for Functional Programming in Java 8 - Working Files/Chapter 2/CleanerCode2.java: 63 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* Review of 'qsort semantics' for sorting functions, including
   ones in Java.

   ## callback that the sorting module uses
   int compare(item1, item2)   ## item1 and item2 are (references to) items to be sorted
                               ## their order is important: item1 is 1st, item2 is 2nd
   
   Semantics of return value:
   
      0 means the items are equal for the sort

      < 0 means that the 1st (item1) should precede the 2nd (item2)

      > 0 means that the 2nd (item2) should precede the 1st (item1)
*/

import java.util.Arrays;
import java.util.Random;
import java.util.Comparator;

public class CleanerCode2 {
    public static void main(String[ ] args) {
	new CleanerCode2().doIt();
    }

    // a Comparator to use in sorting the array
    // compiler generates CleanerSyntax2$1.class
    public static Comparator<Integer> intNumC = new Comparator<Integer>() {
	@Override
	public int compare(Integer n1, Integer n2) {
	    return n2 - n1; // descending order
	}
    };

    private void doIt() {
	Integer[ ] nums = new Integer[32];

	// old way
	populate(nums);
	dump("Unsorted: ", nums);
	Arrays.sort(nums, intNumC);
	dump("Sorted:   ", nums);
	System.out.println();

	// new way
	populate(nums);
	dump("Unsorted: ", nums);
	Arrays.sort(nums, (n1, n2) -> n2 - n1); //## ...and the winner is...
	dump("Sorted:   ", nums);
	System.out.println();
    }

    private void populate(Integer[ ] nums) {
	Random r = new Random();
	for (int i = 0; i < nums.length; i++) 
	    nums[i] = r.nextInt(100);  // 2 digits at most for readability
    }
    private void dump(String msg, Integer[ ] nums) {
	System.out.print("\n" + msg);
	for (Integer n : nums) System.out.print(n + " ");
    }
}
+54 −0
Changes for Functional Programming in Java 8 - Working Files/Chapter 2/Intro2FP.java: 54 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* Compile and run in the usual way, but Java8 is required. */

@FunctionalInterface // strictly optional -- can be omitted and usually is
interface BinaryIntOp {
    // A FunctionalInterface declares a single (abstract) method, in this case named 'compute'.
    // A reference of a FunctionalInterface type can be the target for a lambda expression assignment,
    // given that the lambda expression takes the same number of arguments and returns the same type.
    // There are four such assignments in the code example below.
    abstract int compute(int arg1, int arg2); // takes two ints as args, returns an int
}

public class Intro2FP {
    public static void main(String args[ ]) {
	new Intro2FP().demo();
    }
    
    //## lambda syntax in Java:
    //
    //    argList -> body   ## arrow -> separates argList from body
    //
    //## If there's only a single arg, the arg list need not be parenthesized; but it may be.
    //## (Easiest simply to parenthesize the arg list in all cases.)
    //## The body executes, presumably using the arguments in the argList.
    private void demo() {
	// 1: typed parameters, body is an explicit block with a return statement
	BinaryIntOp add = (int arg1, int arg2) -> { return arg1 + arg2; };  //## add = <lamdba>
	
	// 2: typed parameters, body is an expression
	BinaryIntOp sub = (int arg1, int arg2) -> (arg1 - arg2);            //## sub = <lambda>

	// 3: typed parameters, no parentheses in the body's expression
	BinaryIntOp mul = (int arg1, int arg2) -> arg1 * arg2;              //## mul = <lambda>

	// 4: parameters aren't typed -- compiler figures it out
	BinaryIntOp div = (arg1, arg2) -> arg1 / arg2;                      //## div = <lamdba>

	int a1 = 18, a2 = 5;
	System.out.println("\n1st and 2nd args are: " + a1 + " " + a2 + "\n");
	System.out.println("Addition:       " + add.compute(a1, a2)); // 23
	System.out.println("Subtraction:    " + sub.compute(a1, a2)); // 13
	System.out.println("Multiplication: " + mul.compute(a1, a2)); // 90
	System.out.println("Divsion:        " + div.compute(a1, a2)); // 3
    }
}
/* Output:
   1st and 2nd args are: 18 5

   Addition:       23
   Subtraction:    13
   Multiplication: 90
   Divsion:        3
*/

Loading