Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Java Programming 51037 Adam Gerber, PhD, SCJP

Similar presentations


Presentation on theme: "Advanced Java Programming 51037 Adam Gerber, PhD, SCJP"— Presentation transcript:

1 Advanced Java Programming 51037 Adam Gerber, PhD, SCJP gerber@uchicago.edu

2 2 Lecture 01-02 Agenda: 1/ intro to course and introductions 2/ BitBucket register 3/ Course logistics 4/ Quick review of Java and ecosystem 5/ Maven 6/ Git 7/ Serialization and I/O 8/ Behavior Parameterization 9/ Streams (lecture 2) 10/ Some Design Patterns

3 3 Survey of the class Your name, hailing from, what you studied in undergrad, what you want to accomplish with this degree?

4 4 51037 is a Graduate Seminar You will be expected to do original research on Java and Java ecosystem technologies. You will be expected to present your research to the class.

5 5 Team Projects Each team will be responsible for: 1/ creating a deck of slides describing the architecture of the technology Each team member will be responsible for: 1/ creating a lab using the course tools Maven/Git/IntelliJ and making their lab available on bitbucket as public repo. 2/ lecturing for 1/2 hour on that lab in weeks 8 or 9. See course website for dates: http://java- class.cs.uchicago.edu/adv/

6 6 Website Course website: http://java-class.cs.uchicago.edu/adv/

7 7 Using Slack h ttps://mythicmobile.slack.com/messages/aj2016/

8 8 Registering Bitbucket account Remote source-control: http://java-class.cs.uchicago.edu/adv/

9 9 Policy regarding As Max 30% As awarded in any class. There are a lot of smart people in this room. You will need to do extraordinarily good work to get an A.

10 10 Brief review Java Java is the McGyver of programming languages aka the duct tape of Enterprise programming. Java has a huge eco-system of technologies that work with it.

11 11 Java Java is Write Once Run Anywhere (WORA). A java program can run on any platform that has a JVM. A Java WAR file can run on any JEE compliant web-server, such as Tomcat, JBoss, Wirefly, Glassfish. Java Messaging Service for interoperability flows and microservices. You WILL see Java at your job – it is practically unavoidable.

12 12 What Sun (now Oracle) says about Java “…we designed Java as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that, in our experience, bring more grief than benefit.” “The network is the computer” Sun Micro Java has support for concurrency since version 1.0.

13 13

14 14

15 15 Architecture Neutral Java Code is compiled to.class files which are interpreted as bytecode by the JVM. (.NET does this too; only you’re trapped in an MS op system.) JIT compilers like HotSpot are very fast – little difference between in performance between machine-binary and interpreted byte-code.

16 16 Java8 is OO “AND” Functional Java is Object-Oriented. Java code must be encapsulated inside a class. No procedural programming; and no spaghetti code. Java8 is now functional and allows for lambdas, streams, and parallel programming.

17 17 Implementation Independence A java int is ALWAYS 32bits; regardless of operating system. A java long is ALWAYS 64bits. hashcode() will always be consistent. Serialization is versioned and consistent. The same is not true of C/C++.

18 18 No Pointers There are no pointers in Java Instead Java uses references; which for all intents and purposes, behave like pointers. C++ is like driving a manual transmission car, Java is like driving an automatic transmission car, and python is like sitting in an uber cab.

19 19 Version numbers in Java Jdk1.5 == Java 5.0 Jdk1.6 == Java 6.0 Jdk1.7 == Java 7.0 Jdk1.8 == Java 8.0

20 20 Wrapper Classes Every primitive has a corresponding Wrapper class. For example; double has Double, int has Integer, boolean has Boolean, char has Character, etc. These wrapper classes can be very useful when storing values in collections which require you to use objects, and forbid the use of primitives. Useful for Streams.

21 21 The API Documentation of the Standard Java Library http://docs.oracle.com/javase/8/docs/api/ Directly within IntelliJ via Cntrl+N (check box non- project files)

22 22 Object heirarchies You can also see the API online. Determine the version you're using by typing> java –version http://docs.oracle.com/javase/8/docs/api/ Class hierarchies. The Object class is the grand-daddy of ALL java classes. Every class inherits methods from Object. And from all its other ancestry. Even if you create a class that extends no other classes, you still extend Object by default.

23 23 Class Object A blueprint is to a house as a class is to an object Class = Blueprint

24 24 Lambda Function Functions are now first-class citizens Store a method in a Lambda for deferred execution.

25 25 pass by value pass by reference Action: Tell my accountant how much I intend to spend on a new car. Change in bank account: no change. Action: Swipe debit card and enter pin at the Bently dealership. Change in bank account: -125k.

26 26 Passing references around is dangerous, particularly in a multithreaded environment. Java8 prefers recursion over iteration, and stateless over stateful (side-effects).

27 27 Maven

28 What is Maven? A build tool A documentation toolA dependency management tool

29 Maven makes your builds boring… Building projects should be easy and standardized. You should not be spending a substantial amount of your project time on builds. Builds should just work!

30 Benefits of Maven Portability and Standardization Fast and easy to set up a powerful build process Dependency management (automatic downloads) Project website generation, Javadoc Continuous Integration Server automatic Very useful for TDD and testing

31 Installation and Setup Download Maven from http://maven.apache.org/ http://maven.apache.org/ Unzip the distribution Create environment variable M2_HOME, which points to Maven directory, e.g. c:\tools\apache-maven-3.1.0 Add Maven’s bin directory to System Variable Path Ensure JAVA_HOME is set to JDK Run mvn –version to test install C:\Users\alina.vasiljeva>mvn -version Apache Maven 3.1.0 (893ca28a1da9d5f51ac03827af98bb730128f9f2; 2013-06-28 05:15:32+0300) Maven home: C:\tools\apache-maven-3.1.0\bin\..

32 32 Maven Background Is a Java build tool  “project management and comprehension tool” An Apache Project  Mostly sponsored by Sonatype History  Maven 1 (2003) Very Ugly Used in Stack 1  Maven 2 (2005) Complete rewrite Not backwards Compatible Used in Stack 2.0,2.1,2.2,3.0  Maven 3 (2010) Same as Maven 2 but more stable Used in Stack 2.3, 3.1

33 33 The Maven Mindset All build systems are essentially the same:  Compile Source code  Link resources and dependencies  Compile and Run Tests  Package Project  Deploy Project  Cleanup

34 34 Other Java Build Tools Ant (2000)  Granddaddy of Java Build Tools  Scripting in XML  Very flexible Ant+Ivy (2004)  Ant but with Dependency Management Gradle (2008)  Attempt to combine Maven structure with Groovy Scripting  Easily extensible

35 35 Maven Learning Resources Maven Homepage  http://maven.apache.org Reference Documentation for Maven Reference Documentation for core Plugins Sonatype Resources  http://www.sonatype.com/resource-center.html Free Books Videos

36 36 Project Name (GAV) Maven uniquely identifies a project using:  groupID: Arbitrary project grouping identifier (no spaces or colons) Usually loosely based on Java package  artfiactId: Arbitrary name of project (no spaces or colons)  version: Version of project Format {Major}.{Minor}.{Maintanence} Add ‘-SNAPSHOT ‘ to identify in development GAV Syntax: groupId:artifactId:version 4.0.0 org.lds.training maven-training 1.0 Check version and create a new maven quickstart project from CLI

37 37 Maven Conventions Maven is opinionated about project structure target: Default work directory src: All project source files go in this directory src/main: All sources that go into primary artifact src/test: All sources contributing to testing project src/main/java: All java source files src/main/webapp: All web source files src/main/resources: All non compiled source files src/test/java: All java test source files src/test/resources: All non compiled test source files

38 38 Maven Build Lifecycle A Maven build follow a lifecycle Default lifecycle  compile  test  package  Install  site  deploy

39 39 Example Maven Goals To invoke a Maven build you set a lifecycle “goal” mvn install  Invokes generate* and compile, test, package, integration-test, install mvn clean  Invokes just clean mvn clean compile  Clean old builds and execute generate*, compile mvn compile install  Invokes generate*, compile, test, integration-test, package, install mvn test clean  Invokes generate*, compile, test then cleans

40 40 Maven and Dependencies Maven revolutionized Java dependency management  No more checking libraries into version control Introduced the Maven Repository concept  Established Maven Central Created a module metadata file (POM) Introduced concept of transitive dependency Often include source and javadoc artifacts

41 41 Adding a Dependency Dependencies consist of:  GAV  Scope: compile, test, provided (default=compile). Provided are those that are provided at runtime by the Server for example.  Type: jar, pom, war, ear, zip (default=jar)... javax.servlet servlet-api 2.5 provided

42 42 Maven Repositories Dependencies are downloaded from repositories  Via http Downloaded dependencies are cached in a local repository  Usually found in ${user.home}/.m2/repository Repository follows a simple directory structure  {groupId}/{artifactId}/{version}/{artifactId}-{version}.jar  groupId ‘.’ is replaced with ‘/’ Maven Central is primary community repo  http://repo1.maven.org/maven2 Check the local system for.m2 dependencies

43 43 Proxy Repositories Proxy (Private) Repositories are useful:  Organizationally cache artifacts  Allow organization some control over dependencies  Combines repositories

44 44 Defining a repository Private repositories are defined in the pom Repositories can be inherited from parent Repositories are keyed by id Downloading snapshots can be controlled... lds-main LDS Main Repo http://code.lds.org/nexus/content/groups/main-repo false

45 45 Transitive Dependencies Transitive Dependency Definition:  A dependency that should be included when declaring project itself is a dependency ProjectA depends on ProjectB If ProjectC depends on ProjectA then ProjectB is automatically included Only compile and runtime scopes are transitive Transitive dependencies are controlled using:  Exclusions  Optional declarations

46 46 Dependency Exclusions Exclusions exclude transitive dependencies Dependency consumer solution... org.springframework spring-core 3.0.5.RELEASE commons-logging

47 47 Dependency Management What do you do when versions collide?  Allow Maven to manage it? Complex and less predictable  Take control yourself Manage the version manually In Java you cannot use both versions... org.springframework spring-core 3.0.5.RELEASE

48 Super POM Convention over configuration. The Super POM is Maven's default POM All POMs extend the Super POM unless explicitly set The configuration specified in the Super POM is inherited by the POMs you created for your projects Super POM snippet can be found here: http://maven.apache.org/guides/introduction/introduction- to-the-pom.html

49 Standard directory organization Having a common directory layout would allow for users familiar with one Maven project to immediately feel at home in another Maven project. src/main/javaApplication/Library sources src/main/resourcesApplication/Library resources src/main/filtersResource filter files src/main/assemblyAssembly descriptors src/main/configConfiguration files src/main/webappWeb application sources src/test/javaTest sources src/test/resourcesTest resources src/test/filtersTest resource filter files src/siteSite LICENSE.txtProject's license README.txtProject's readme

50 Overview of common Goals validate - validate the project is correct and all necessary information is available compile - compile the source code of the project test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed. package - take the compiled code and package it in its distributable format, such as a JAR integration-test - process and deploy the package if necessary into an environment where integration tests can be run install - install the package into the local repository, for use as a dependency in other projects locally site – create documentation for the project. deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects

51 Add a dependency Add a new dependency in pom.xml 4.0.0 com.web.music my_project jar 1 my_project log4j 1.2.17 Create a new quickstart app and add StringEscapeUtils dependency

52 Maven console output C:\Temp\my-app>mvn compile [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building my-app 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------... Downloading: http://repo1.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar Downloaded: http://repo1.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar (359 KB at 49.4 KB/sec) [INFO] Not writing settings - defaults suffice [INFO] Wrote Eclipse project for "my-app" to C:\Temp\my-app. [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.302s [INFO] Finished at: Mon Sep 12 19:34:32 EEST 2012 [INFO] Final Memory: 9M/153M [INFO] ------------------------------------------------------------------------

53 Local repository What does Maven do with all the dependencies?  C:\Documents and Settings\ \.m2 Advantages: No need to keep anything in the repo other than your own source code, saves space in the repo and rebuild / transfer time Can download dependencies from a local intranet repo instead of repo1.maven.org, etc IntelliJ needs to know the path to the local Maven repository. Therefore the classpath variable M2_REPO has to be set: Java > Build Path > Classpath Variables

54 Installing JARs to local repository Sometimes you need to put some specific JARs in your local repository for use in your builds The JARs must be placed in the correct place in order for it to be correctly picked up by Maven To install a JAR in the local repository use the following command: Now can include dependency in pom.xml: mvn install:install-file -Dfile= -DgroupId= \ -DartifactId= -Dversion= -Dpackaging=jar

55 Creating project website Execute mvn site goal Maven will start downloading and creating things left and right Eventually in the \target dir you end up with a \site dir, with an apache-style project website Javadoc, various reports, and custom content can be added run mvn site on jaLabJava

56 Website features Continuous Integration Dependencies (JUnit is listed) Issue Tracking Mailing Lists Project License Project Team Source Repository

57 Using Maven Plugins Plugins in Maven 2.0 look much like a dependency For example, configure the Java compiler to allow JDK 6.0 sources... org.apache.maven.plugins maven-compiler-plugin 1.6...

58 Good things about Maven Standardization Reuse Dependency management Build lifecycle management Large existing repository IDE aware One directory layout A single way to define dependencies Setting up a project is really fast Transitive dependencies Common build structure Use of remote repository Web site generation Build best practices enforcement Automated build of application Works well with distributed teams All artifacts are versioned and are stored in a repository Build process is standardized for all projects A lot of goals are available It provides quality project information with generated site Easy to learn and use Makes the build process much easier at the project level Promotes modular design of code Many, many templates!

59 Alternatives There are also alternative build tools An up-and-coming star in the build world. Groovy, Ant and Ivy combined. Ruby Java building with Maven repositories http://www.streamhead.com/maven-alternatives/ The agile dependency manager from Apache

60 References Maven Home http://maven.apache.org/ Maven Getting Started Guide http://maven.apache.org/guides/getting-started/index.html Steps for creating a Maven-based Website http://www.javaworld.com/javaworld/jw-02-2006/jw-0227-maven_p.html Maven 3 Plugins Project http://mojo.codehaus.org/

61 Where to install maven? https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html why modelVersion in a maven file? http://stackoverflow.com/questions/19759338/why-modelversion-of-pom-xml-is- necessary-and-always-set-to-4-0-0 mvn archetype:generate -DgroupId=edu.uchicago.gerber.ajava -DartifactId=maven02 - DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false StringEscapeUtils https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html Hello from Html. StringEscapeUtils.escapeHtml4(paragraph); use site to generate documentation http://books.sonatype.com/mvnref-book/reference/site-generation-sect-custom- descript.html

62 62 Git A distributed version control system 9/29/2016

63 Git History Came out of Linux development community Linus Torvalds, 2005 Initial goals: Speed Support for non-linear development (thousands of parallel branches) Fully distributed Able to handle large projects like Linux efficiently

64 64 When I say I hate CVS with a passion, I have to also say that if there are any SVN [Subversion] users in the audience, you might want to leave. Because my hatred of CVS has meant that I see Subversion as being the most pointless project ever started. The slogan of Subversion for a while was "CVS done right", or something like that, and if you start with that kind of slogan, there's nowhere you can go. There is no way to do CVS right. --Linus Torvalds, as quoted in Wikipedia

65 Git uses a distributed model Centralized ModelDistributed Model (CVS, Subversion, Perforce) (Git, Mercurial) Result: Many operations are local

66 Git uses checksums In Subversion each modification to the central repo incremented the version # of the overall repo. How will this numbering scheme work when each user has their own copy of the repo, and commits changes to their local copy of the repo before pushing to the central server????? Instead, Git generates a unique SHA-1 hash – 40 character string of hex digits, for every commit. Refer to commits by this ID rather than a version number. Often we only see the first 7 characters: 1677b2d Edited first line of readme 258efa7 Added line to readme 0e52da7 Initial commit

67 Get ready to use Git! 1.Set the name and email for Git to use when you commit: $ git config --global user.name “Bugs Bunny” $ git config --global user.email bugs@gmail.com 1.You can call git config –list to verify these are set. 2.These will be set globally for all Git projects you work with. 3.You can also set variables on a project-only basis by not using the --global flag. 4.You can also set the editor that is used for writing commit messages: $ git config --global core.editor emacs(it is vim by default)

68 68 mvn archetype:generate - DarchetypeGroupId=org.codehaus.mojo.archetypes - DarchetypeArtifactId=javafx Assuming you already have either a maven or intellij project. Make sure you have the.ignore plugin Select the project view from the project window drop-down On the main menu, choose VCS | Import into Version Control | Create Git Repository. By default, IntelliJ IDEA suggests the root of the current project, but select the root if not selected. Right click the root dir in the project window and select new ||.ignore || git.ignore search for JetBrains and Maven and allow the.gitignore plugin to generate a new.ignore file for you. Create a new javafx quickstart project and call it proClient, proImageshop

69 69 Right click root directory from the project window again and select || Git || Add You will see all the files turn green (except those being ignored which will be muted grey) Create a remote on bitbucket by going to bitbucket.org repository | create repository give the project a name (probably best to give it the same name as the local project). Go to access management and add: csgerber, johnhb, davidselvaraj with READ access click on overview on the left panel click on the "I have an existing project" drop-down copy the second line into the clipboard -- the one that looks similar to this: git remote add origin git@bitbucket.org:csgerber/proclient.git

70 70 open a terminal in intelliJ paste contents of clipboard and press enter. Test that you did it correctly by typing: git remote -v From intelliJ, press Command + K or Ctrl + K uncheck all checkboxes on right type your commit message such as "initial commit." commit || push make changes to the working directory and always remember if prompted to add files to git, add them. commit || push as required ad infititum.

71 Version control systems Version control is all about managing multiple versions of documents, programs, web sites, etc. Almost all “real” projects use some kind of version control Essential for team projects, but also very useful for individual projects Some well-known version control systems are CVS, Subversion, Mercurial, and Git CVS and Subversion use a “central” repository; users “check out” files, work on them, and “check them in” Mercurial and Git treat all repositories as equal Distributed systems like Mercurial and Git are newer and are gradually replacing centralized systems like CVS and Subversion 71

72 Why version control? For working by yourself: Gives you a “time machine” for going back to earlier versions Gives you great support for different versions (standalone, web app, etc.) of the same basic project For working with others: Greatly simplifies concurrent work, merging changes Create a portfolio of projects 72

73 Introduce yourself to Git Enter these lines (with appropriate changes): git config --global user.name "John Smith" git config --global user.email jsmith@seas.upenn.edu You only need to do this once If you want to use a different name/email address for a particular project, you can change it for just that project cd to the project directory Use the above commands, but leave out the --global 73

74 Git Resources At the command line: (where verb = config, add, commit, etc.) $ git help $ git --help $ man git- Free on-line book: http://git-scm.com/bookhttp Git tutorial: http://schacon.github.com/git/gittutorial.html Reference page for Git: http://gitref.org/index.html Git website: http://git-scm.com/ Git for Computer Scientists (http://eagain.net/articles/git- for-computer-scientists/)

75 A Local Git project has three areas Unmodified/modified Files Staged Files Committed Files Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.

76 76 Fork, clone the lab, then create new remote called gerber.

77 77 The difference between a fork and a clone A fork is NOT a git operation. It is an operation of a Git Web Hosting Service like Bitbucket or Github. A clone is a git operation. It creates a local copy of the remote repo.

78 78

79 79

80 Git file lifecycle

81 81 How IntelliJ stages files. Examine SourceTree versus CLI versus IntelliJ. IntelliJ defers staging until the last step (Cmd+K or Ctrl+K) In CLI or SourceTree, you just stage before committing.

82 82 add/reset/commit: move files from working-dir to stage-dir(aka index) git add. git add src/. git add src/lec01/glab/DigitalToBinary.java move files from stage-dir(aka index) to working-dir git reset HEAD. git reset head src/. git reset head src/lec01/glab/DigitalToBinary.java git commit -m “your commit message.”

83 83 Amending: Every commit is associated with a sha-1 hash. That hash is derived from 1/ the file changes in that commit and 2/ the previous commit. You can not change any commit unless that commit is at the head. Since no other commits depend on the head, you may safely change the head. To change the head, use git commit --amend -m “your message” git commit --amend --no-edit

84 84 Reverting: You can roll back a commit (reverse it) by identifying it's sha1 hash like so. git revert --no-edit 71ac

85 85 Branching: To list the branches in a project: git branch git branch -r git branch --all To create a branch: git checkout -b branchName c39b git checkout -b branchName To delete a branch: git branch -D branchName To checkout a branch: git checkout 7afe git checkout master

86 86 Pushing to remotes: To see the remotes: git remote -v To push to a remote: git push origin master:master git push origin master git push --all

87 87 Pulling from remotes: To see the remotes: git remote -v To pull from a remote: git pull --all git pull origin eval

88 88 Show the history of a single file in IntelliJ How to resolve merge conflicts. How to force push a branch How to delete a remote branch How to do a FFWD merge

89 Basic Workflow in IntelliJ Basic Git workflow: 1.Modify files in your working directory. 2.Do a commit, (Cmd+K, or Ctrl+K) which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory.

90 Create a local copy of a repo 2.Two common scenarios: (only do one of these) a)To clone an already existing repo to your current directory: $ git clone [local dir name] This w ill create a directory named local dir name, containing a working copy of the files from the repo, and a.git directory (used to hold the staging area and your actual repo) b)To create a Git repo in your current directory: $ git init This will create a.git directory in your current directory. Then you can commit files in that directory into the repo: $ git add file1.java $ git commit –m “initial project version ”

91 Status To view the status of your files in the working directory and staging area: $ git status or $ git status –s (-s shows a short one line version similar to svn)

92 Show Diff To see the Diff between the working directory and the local git repo, press Ctrl+K or Cmd+K. Examine the files and cancel

93 Searching commits You can use the filter ominbox to search for a particular commit. You can sort by Author or date as well.

94

95 Git color coding for files in IntelliJ Untracked files are brown (dark orange). New files are green. Modified files are blue. Settled files in repo are black. Ignored files are muted gray. Conflicted files are red.

96 Dealing with untracked files Dragging a file into your project (not added to git automatically)

97 Viewing logs (same as log in IntelliJ) To see a log of all changes in your local repo: $ git log or $ git log --oneline (to show a shorter version) 1677b2d Edited first line of readme 258efa7 Added line to readme 0e52da7 Initial commit git log -5 (to show only the 5 most recent updates, etc.) Note: changes will be listed by commitID #, (SHA-1 hash) Note: changes made to the remote repo before the last time you cloned/pulled from it will also be included here

98 SVN vs. Git SVN: central repository approach – the main repository is the only “true” source, only the main repository has the complete file history Users check out local copies of the current version Git: Distributed repository approach – every checkout of the repository is a full fledged repository, complete with history Greater redundancy and speed Branching and merging repositories is more heavily used as a result

99 Imperative versus Declarative Imperative: is a style of programming where you program the algorithm with control flow and explicit steps. Declarative: is a style of programming where you declare what needs be done without concern for the control flow. Functional programming: is a declarative programming paradigm that treats computation as a series of functions and avoids state and mutable data to facilitate concurrency. “Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate computability, the Entscheidungsproblem, function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus”. Wikipedia See BigDecimalMain

100 100 Behavior Parameterization

101 How did Java deal with “functional” programming prior to Java8 Urma/behaviorParam/_01TheProblemDefined

102 Another example of anon class

103 Our first Lambda expression 1/ start with a “functional interface” - a functional interface has ONE abstract method. 2/ create an anonymous class and implement its method 3/ use the format as seen above 4/ no need for return statements, that's implied

104 Another example

105

106 Type of Lambda Expression The java ‘Type’ of a lamba expression is a “Functional Interface” Functional Interface is an interface with only ONE abstract method The concept of “Functional Interface” is new, but many of the interfaces in Java7 and before are “functional interfaces” such as Runnable, Comparable, etc. Java8 defines many more functional interfaces in the java.util.function.* pacakge. Older functional interfaces have been decorated with default methods to preserve backwards compatibility

107 Location of Functional Interfaces You may define your own “Functional Interfaces” Java8 defines many in: java.util.function.* 43 interfaces in 4 categories, such as Function, Supplier, Consumer, Predicate.

108 Can I store a Lamba Expression in a variable in Java? Yes! Wherever a method requires an anonymous inner class (with one method), you may put a lamba expression. For example: Collections.sort(list, compL); You may also use lambda expressions with Streams See functionalIterfaceTest

109 Is a Lambda expression an Object? Not really. It is an ‘object without identity’. It does not inherit from Object and so you can’t call the.equals(),.hashcode(), etc. There is no ‘new’ keyword in lamba, so there is far less overhead both at compile- and run-time. You can't use this keyword to identify it using reflection.

110

111 111 References A lot of the material in this lecture is discussed in much more detail in these informative references: The Java Tutorials, http://docs.oracle.com/javase/tutorial/java/index.html Lambda Expressions, http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaex pressions.html Adib Saikali, Java 8 Lambda Expressions and Streams, www.youtube.com/watch?v=8pDm_kH4YKY Brian Goetz, Lambdas in Java: A peek under the hood. https://www.youtube.com/watch?v=MLksirK9nnE

112 112 Event (onClick) No Event-Listener listening No Catcher Event-Source (Button) No Event Listener

113 113 Event (onClick) Event-Listener listening Catcher ready to catch Event-Source (Button) OnClick- Listener Any Object

114 114 Behavior Parameterization Objects are first-class citizens in Java. You can now store references to functions. Functions too are first class citizens in Java.

115 115 The Lambda Calculus The lambda calculus was introduced in the 1930s by Alonzo Church as a mathematical system for defining computable functions. The lambda calculus serves as the computational model underlying functional programming languages such as Lisp, Haskell, and Ocaml. Features from the lambda calculus such as lambda expressions have been incorporated into many widely used programming languages like C++ and now very recently Java 8.

116 116 Example of a Lambda Expression The lambda expression λ x. (x + 1) 2 represents the application of a function λ x. ( x + 1) with a formal parameter x and a body x + 1 to the argument 2. Notice that the function definition λ x. ( x + 1 ) has no name; it is an anonymous function. In Java 8, we would represent this function definition by the Java 8 lambda expression x -> x + 1.

117 117 More Examples of Java 8 Lambdas A Java 8 lambda is basically a method in Java without a declaration usually written as (parameters) -> { body }. Examples, 1. (int x, int y) -> { return x + y; } 2. x -> x * x 3. ( ) -> x A lambda can have zero or more parameters separated by commas and their type can be explicitly declared or inferred from the context. Parenthesis are not needed around a single parameter. ( ) is used to denote zero parameters. The body can contain zero or more statements. Braces are not needed around a single-statement body.

118 118 What is Functional Programming? A style of programming that treats computation as the evaluation of mathematical functions Eliminates side effects Treats data as being immutable Expressions have referential transparency – this reference will do this and this only. Functions can take functions as arguments and return functions as results Prefers recursion over explicit for-loops

119 119 Why do Functional Programming? Allows us to write easier-to-understand, more declarative, more concise programs than imperative programming Allows us to focus on the problem rather than the code Facilitates parallelism

120 120 Java 8 Java 8 is the biggest change to Java since the inception of the language Lambdas are the most important new addition Java is playing catch-up: most major programming languages already have support for lambda expressions A big challenge was to introduce lambdas without requiring recompilation of existing binaries

121 121 Benefits of Lambdas in Java 8 Enabling functional programming Writing leaner more compact code Facilitating parallel programming Developing more generic, flexible and reusable APIs Being able to pass behaviors as well as data to functions

122 122 Java 8 Lambdas Syntax of Java 8 lambda expressions Functional interfaces Variable capture Method references Default methods

123 123 Example 1: Print a list of integers with a lambda List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x)); x -> System.out.println(x) is a lambda expression that defines an anonymous function with one parameter named x of type Integer

124 124 Example 2: A multiline lambda List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { x += 2; System.out.println(x); }); Braces are needed to enclose a multiline body in a lambda expression.

125 125 Example 3: A lambda with a defined local variable List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { int y = x * 2; System.out.println(y); }); Just as with ordinary functions, you can define local variables inside the body of a lambda expression

126 126 E xample 4: A lambda with a declared parameter type List intSeq = Arrays.asList(1,2,3); intSeq.forEach((Integer x -> { x += 2; System.out.println(x); }); You can, if you wish, specify the parameter type.

127 127 Functional Interfaces Design decision: Java 8 lambdas are assigned to functional interfaces. A functional interface is a Java interface with exactly one non- default method. E.g., public interface Consumer { void accept(T t); } The package java.util.function defines many new useful functional interfaces.

128 128 Implementation of Java 8 Lambdas The Java 8 compiler first converts a lambda expression into a function It then calls the generated function For example, x -> System.out.println(x) could be converted into a generated static function public static void genName(Integer x) { System.out.println(x); } Urma/behaviorParam/UsingConsumers.java

129 129 Variable Capture Lambdas can interact with variables defined outside the body of the lambda Using these variables is called variable capture These variables must be effectively final.

130 130 Local Variable Capture Example public class LVCExample { public static void main(String[] args) { List intSeq = Arrays.asList(1,2,3); int var = 10; intSeq.forEach(x -> System.out.println(x + var)); } Note: local variables used inside the body of a lambda must be final or effectively final

131 131 Static Variable Capture Example public class SVCExample { private static int var = 10; public static void main(String[] args) { List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x + var)); }

132 132 Method References Method references can be used to pass an existing function in places where a lambda is expected The signature of the referenced method needs to match the signature of the functional interface method

133 133 Summary of Method References Method Reference Type SyntaxExample staticClassName::StaticMethodNameString::valueOf constructorClassName::newArrayList::new specific object instance objectReference::MethodNamex::toString arbitrary object of a given type ClassName::InstanceMethodNameObject::toString

134 134 Conciseness with Method References We can rewrite the statement intSeq.forEach(x -> System.out.println(x)); more concisely using a method reference intSeq.forEach(System.out::println);

135 135 Default Methods Java 8 uses lambda expressions and default methods in conjunction with the Java collections framework to achieve backward compatibility with existing published interfaces For a full discussion see Brian Goetz, Lambdas in Java: A peek under the hood. https://www.youtube.com/watch?v=MLksirK9nnE

136 Streams

137 What is a Stream A stream is a limitless iterator that allows you to process collections. You can chain operations. This chain is called a pipeline. You must have at least one terminal operation and zero or more intermediary operations. The pipeline usually takes the form of map-filter-reduce pattern. Any stream operation that returns a Stream is an intermediate operation, and any object that returns void is terminal. Intermediate operations are lazy, whereas terminal operations are eager. A terminal operation will force the stream to be “spent” and you can NOT re-use that reference, though you can always get a new stream. May be parallelized and optimized across cores. See StreamMain

138 Iterator See IteratorDriver

139 4 categories of Functional Interfaces Functional Interface archetypes Example used in ConsumerforEach(Consumer), peek(Consumer) Predicatefilter(Predicate) Functionmap(Function) Supplierreduce(Supplier) collect(Supplier) See java.util.function.* ConsumerMain

140 4 categories of Functional Interfaces

141 Method references You can refer to static or non-static method simply by using the double colon (method reference) notation like so: System.out::println stringLenComparator::compare See MethodRefsMain

142 Map is a transform The.map() method is not an associative data structure, rather it is a transformative operation. It takes a Stream and it returns either a Stream or Stream. Example: Stream to Stream

143 Intermediary operation Intermediary operation: A method that takes a Stream and returns a Stream. They are lazily loaded and will only be executed if you include a terminal operation at the end. – The peek() method – The map() method – The filter() method

144 Terminal operation Terminal operation: A method that takes a Stream and returns void. They are eagerly loaded and will cause the entire pipeline to be executed. A terminal operation will “spend” the stream. – The forEach() method – The count() method – The max() method – The collect() method – The reduce() method

145 145 Slide references Lambdas: Alfred V. Aho ( http://www.cs.columbia.edu/~aho/cs6998/)http://www.cs.columbia.edu/~aho/cs6998/

146 146 Stream API The new java.util.stream package provides utilities to support functional-style operations on streams of values. A common way to obtain a stream is from a collection: Stream stream = collection.stream(); Streams can be sequential or parallel. Streams are useful for selecting values and performing actions on the results.

147 147 Stream Operations An intermediate operation keeps a stream open for further operations. Intermediate operations are lazy. A terminal operation must be the final operation on a stream. Once a terminal operation is invoked, the stream is consumed and is no longer usable.

148 148 Example Intermediate Operations filter excludes all elements that don’t match a Predicate. map performs a one-to-one transformation of elements using a Function.

149 149 A Stream Pipeline A stream pipeline has three components: 1. A source such as a Collection, an array, a generator function, or an IO channel; 2. Zero or more intermediate operations; and 3. A terminal operation

150 150 Stream Example int sum = widgets.stream().filter(w -> w.getColor() == RED).mapToInt(w -> w.getWeight()).sum(); Here, widgets is a Collection. We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight. From Java Docs Interface Stream

151 151 Parting Example: Using lambdas and stream to sum the squares of the elements on a list List list = Arrays.asList(1,2,3); int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get(); System.out.println(sum); Here map(x -> x*x) squares each element and then reduce((x,y) -> x + y) reduces all elements into a single number http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

152 152 Outline 1. What is the lambda calculus? 2. What is functional programming? 3. What are the benefits of functional programming? 4. Functional programming in Java 8 5. Java 8 lambda expressions 6. Implementation of Java 8 lambda expressions 7. Streams


Download ppt "Advanced Java Programming 51037 Adam Gerber, PhD, SCJP"

Similar presentations


Ads by Google