d1683b495de3ca7c2a9ead1930cec64b.ppt
- Количество слайдов: 151
Advanced Java Programming 51037 Adam Gerber, Ph. D, SCJP gerber@uchicago. edu
Lecture 01 -02 Agenda: 1/ intro to course and introductions 2/ Bit. Bucket 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 2
Survey of the class Your name, hailing from, what you studied in undergrad, what you want to accomplish with this degree? 3
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. 4
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/Intelli. J 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: //javaclass. cs. uchicago. edu/adv/ 5
Website Course website: http: //java-class. cs. uchicago. edu/adv/ 6
Using Slack https: //mythicmobile. slack. com/messages/aj 2016/ 7
Registering Bitbucket account Remote source-control: http: //java-class. cs. uchicago. edu/adv/ 8
Policy regarding As Max 30% As awarded in any class. There a lot of smart people in this room. You will need to do extraordinarily good work to get an A. 9
Brief review Java • Java is the Mc. Gyver of programming languages aka the duct tape of Enterprise programming. • Java has a huge eco-system of technologies that work with it. 10
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. 11
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. 12
13
14
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 Hot. Spot are very fast – little difference between in performance between machine-binary and 15 interpreted byte-code.
Implementation Independence • A java int is ALWAYS 32 bits; regardless of operating system. • A java long is ALWAYS 64 bits. • hashcode() will always be consistent. • Serialization is versioned and consistent. • The same is not true of C/C++. 17
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. 18
Version numbers in Java • • Jdk 1. 5 == Java 5. 0 Jdk 1. 6 == Java 6. 0 Jdk 1. 7 == Java 7. 0 Jdk 1. 8 == Java 8. 0 19
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. 20
The API Documentation of the Standard Java Library http: //docs. oracle. com/javase/8/docs/api/ Directly within Intelli. J via Cntrl+N (check box non-project files) 21
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. 22
Class Object • A blueprint is to a house as a class is to an object • Class = Blueprint 23
Lambda Function • Functions are now first-class citizens • Store a method in a Lambda for deferred execution. 24
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: -125 k. 25
Passing references around is dangerous, particularly in a multithreaded environment. Java 8 prefers recursion over iteration, and stateless over stateful (side-effects). 26
Maven 27
What is Maven? A build tool A dependency management tool A documentation tool
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!
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
Installation and Setup • Download Maven from http: //maven. apache. org/ • Unzip the distribution • Create environment variable M 2_HOME, which points to Maven directory, e. g. c: toolsapache-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: Usersalina. vasiljeva>mvn -version Apache Maven 3. 1. 0 (893 ca 28 a 1 da 9 d 5 f 51 ac 03827 af 98 bb 730128 f 9 f 2; 2013 -06 -28 05: 15: 32+0300) Maven home: C: toolsapache-maven-3. 1. 0bin. .
Maven Background Is a Java build tool An Apache Project “project management and comprehension tool” Mostly sponsored by Sonatype History Maven 1 (2003) Maven 2 (2005) Very Ugly Used in Stack 1 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 32
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 33
Other Java Build Tools Ant (2000) Ant+Ivy (2004) Granddaddy of Java Build Tools Scripting in XML Very flexible Ant but with Dependency Management Gradle (2008) Attempt to combine Maven structure with Groovy Scripting Easily extensible 34
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 35
Project Name (GAV) Maven uniquely identifies a project using: group. ID: Arbitrary project grouping identifier (no spaces or colons) artfiact. Id: Arbitrary name of project (no spaces or colons) version: Version of project Usually loosely based on Java package Format {Major}. {Minor}. {Maintanence} Add ‘-SNAPSHOT ‘ to identify in development GAV Syntax: group. Id: artifact. Id: version <? xml version="1. 0" encoding="UTF-8"? > <project> <model. Version>4. 0. 0</model. Version> <group. Id>org. lds. training</group. Id> <artifact. Id>maven-training</artifact. Id> <version>1. 0</version> </project> Check version and create a new maven quickstart project from CLI 36
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 37
Maven Build Lifecycle A Maven build follow a lifecycle Default lifecycle compile test package Install site deploy 38
Example Maven Goals To invoke a Maven build you set a lifecycle “goal” mvn install mvn clean Clean old builds and execute generate*, compile mvn compile install Invokes just clean mvn clean compile Invokes generate* and compile, test, package, integration-test, install Invokes generate*, compile, test, integration-test, package, install mvn test clean Invokes generate*, compile, test then cleans 39
Maven and Dependencies Maven revolutionized Java dependency management Introduced the Maven Repository concept No more checking libraries into version control Established Maven Central Created a module metadata file (POM) Introduced concept of transitive dependency Often include source and javadoc artifacts 40
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. <project> Type: jar, pom, war, ear, zip (default=jar) . . . <dependencies> <dependency> <group. Id>javax. servlet</group. Id> <artifact. Id>servlet-api</artifact. Id> <version>2. 5</version> <scope>provided</scope> </dependency> </dependencies> </project> 41
Maven Repositories Dependencies are downloaded from repositories Downloaded dependencies are cached in a local repository Usually found in ${user. home}/. m 2/repository Repository follows a simple directory structure Via http {group. Id}/{artifact. Id}/{version}/{artifact. Id}-{version}. jar group. Id ‘. ’ is replaced with ‘/’ Maven Central is primary community repo http: //repo 1. maven. org/maven 2 Check the local system for. m 2 dependencies 42
Proxy Repositories Proxy (Private) Repositories are useful: Organizationally cache artifacts Allow organization some control over dependencies Combines repositories 43
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 <project>. . . <repositories> <repository> <id>lds-main</id> <name>LDS Main Repo</name> <url>http: //code. lds. org/nexus/content/groups/main-repo</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project> 44
Transitive Dependencies Transitive Dependency Definition: A dependency that should be included when declaring project itself is a dependency Project. A depends on Project. B If Project. C depends on Project. A then Project. B is automatically included Only compile and runtime scopes are transitive Transitive dependencies are controlled using: Exclusions Optional declarations 45
Dependency Exclusions exclude transitive dependencies Dependency consumer solution <project>. . . <dependencies> <dependency> <group. Id>org. springframework</group. Id> <artifact. Id>spring-core</artifact. Id> <version>3. 0. 5. RELEASE</version> <exclusions> <exclusion> <group. Id>commons-logging</group. Id> <artifact. Id>commons-logging</artifact. Id> </exclusions> </dependency> </dependencies> </project> 46
Dependency Management What do you do when versions collide? Allow Maven to manage it? Take control yourself Complex and less predictable Manage the version manually In Java you cannot use both versions <project>. . . <dependency. Management> <dependencies> <dependency> <group. Id>org. springframework</group. Id> <artifact. Id>spring-core</artifact. Id> <version>3. 0. 5. RELEASE</version> </dependency> </dependencies> </dependency. Management> </project> 47
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/introductionto-the-pom. html
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/java Application/Library sources src/main/resources Application/Library resources src/main/filters Resource filter files src/main/assembly Assembly descriptors src/main/config Configuration files src/main/webapp Web application sources src/test/java Test sources src/test/resources Test resources src/test/filters Test resource filter files src/site Site LICENSE. txt Project's license README. txt Project's readme
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
Create a new quickstart app and add String. Escape. Utils dependency Add a dependency • Add a new dependency in pom. xml <project> <model. Version>4. 0. 0</model. Version> <group. Id>com. web. music</group. Id> <artifact. Id>my_project</artifact. Id> <packaging>jar</packaging> <version>1</version> <name>my_project</name> <dependencies> <dependency> <group. Id>log 4 j</group. Id> <artifact. Id>log 4 j</artifact. Id> <version>1. 2. 17</version> </dependency> </dependencies> <build/> </project>
Maven console output C: Tempmy-app>mvn compile [INFO] Scanning for projects. . . [INFO] ------------------------------------[INFO] Building my-app 1. 0 -SNAPSHOT [INFO] ------------------------------------. . . Downloading: http: //repo 1. maven. org/maven 2/log 4 j/1. 2. 1 7/log 4 j-1. 2. 17. jar Downloaded: http: //repo 1. maven. org/maven 2/log 4 j/1. 2. 1 7/log 4 j-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: Tempmy-app. [INFO] ------------------------------------[INFO] BUILD SUCCESS [INFO] ------------------------------------[INFO] Total time: 9. 302 s [INFO] Finished at: Mon Sep 12 19: 34: 32 EEST 2012 [INFO] Final Memory: 9 M/153 M [INFO] ------------------------------------
Local repository • What does Maven do with all the dependencies? C: Documents and Settings<username>. m 2 • 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 repo 1. maven. org, etc • Intelli. J needs to know the path to the local Maven repository. Therefore the classpath variable M 2_REPO has to be set: • Java > Build Path > Classpath Variables
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: mvn install: install-file -Dfile=<path-to-file> -Dgroup. Id=<group-id> -Dartifact. Id=<artifact-id> -Dversion=<version> -Dpackaging=jar • Now can include dependency in pom. xml: <dependency> <group. Id><group-id></group. Id> <artifact. Id><artifact-id></artifact. Id> <version></version> </dependency>
run mvn site on ja. Lab. Java 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
Website features • • Continuous Integration Dependencies (JUnit is listed) Issue Tracking Mailing Lists Project License Project Team Source Repository
Using Maven Plugins • Plugins in Maven 2. 0 look much like a dependency • For example, configure the Java compiler . . . to allow <build> <plugins> JDK 6. 0 <plugin> <group. Id>org. apache. maven. plugins</group. Id> <artifact. Id>maven-compiler-plugin</artifact. Id> sources <configuration> <source>1. 6</source> <target>1. 6</target> </configuration> </plugins> </build>. . .
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!
Alternatives • There also alternative build tools An up-and-coming star in the build world Groovy, Ant and Ivy combined. Ruby Java building with Maven repositori The agile dependency manager from Apache http: //www. streamhead. com/maven-alternatives/
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/
Where to install maven? https: //maven. apache. org/guides/getting-started/maven-in-five-minutes. html why model. Version 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 -Dgroup. Id=edu. uchicago. gerber. ajava -Dartifact. Id=maven 02 Darchetype. Artifact. Id=maven-archetype-quickstart -Dinteractive. Mode=false String. Escape. Utils https: //maven. apache. org/guides/getting-started/maven-in-five-minutes. html <p>Hello from Html. </p> String. Escape. Utils. escape. Html 4(paragraph); use site to generate documentation http: //books. sonatype. com/mvnref-book/reference/site-generation-sect-customdescript. html
Git A distributed version control system 62 3/15/2018
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
When I say I hate CVS with a passion, I have to also say that if there 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 64
Git uses a distributed model Centralized Model Distributed Model (CVS, Subversion, Perforce) (Git, Mercurial) Result: Many operations are local
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
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:
Create a new javafx quickstart project and call it pro. Client, pro. Imageshop mvn archetype: generate Darchetype. Group. Id=org. codehaus. mojo. archetypes Darchetype. Artifact. Id=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, Intelli. J 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 Jet. Brains and Maven and allow the. gitignore plugin to generate a new. ignore file for you. 68
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 69
open a terminal in intelli. J paste contents of clipboard and press enter. Test that you did it correctly by typing: git remote -v From intelli. J, 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. 70
Version control systems • Version control is all about managing multiple versions of documents, programs, web sites, etc. • • • Some well-known version control systems are CVS, Subversion, Mercurial, and Git • • • Almost all “real” projects use some kind of version control Essential for team projects, but also very useful for individual projects 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
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
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
Git Resources • At the command line: (where verb = config, add, commit, etc. ) $ git help <verb> $ git <verb> --help $ man git-<verb> • • Free on-line book: http: //git-scm. com/book Git tutorial: http: //schacon. github. com/gittutorial. html Reference page for Git: http: //gitref. org/index. html Git website: http: //git-scm. com/
A Local Git project has three areas Unmodified/modified Staged Files Committed Files Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.
Fork, clone the lab, then create new remote called gerber. 76
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. 77
78
79
Git file lifecycle
How Intelli. J stages files. Examine Source. Tree versus CLI versus Intelli. J defers staging until the last step (Cmd+K or Ctrl+K) In CLI or Source. Tree, you just stage before committing. 81
add/reset/commit: move files from working-dir to stage-dir(aka index) git add src/lec 01/glab/Digital. To. Binary. java move files from stage-dir(aka index) to working-dir git reset HEAD. git reset head src/lec 01/glab/Digital. To. Binary. java git commit -m “your commit message. ” 82
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 83
Reverting: You can roll back a commit (reverse it) by identifying it's sha 1 hash like so. git revert --no-edit 71 ac 84
Branching: To list the branches in a project: git branch -r git branch --all To create a branch: git checkout -b branch. Name c 39 b git checkout -b branch. Name To delete a branch: git branch -D branch. Name To checkout a branch: git checkout 7 afe git checkout master 85
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 86
Pulling from remotes: To see the remotes: git remote -v To pull from a remote: git pull --all git pull origin eval 87
Show the history of a single file in Intelli. J How to resolve merge conflicts. How to force push a branch How to delete a remote branch How to do a FFWD merge 88
Basic Workflow in Intelli. J 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.
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 <url> [local dir name] This will 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 file 1. java $ git commit –m “initial project version ” $
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)
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
Searching commits • You can use the filter ominbox to search for a particular commit. • You can sort by Author or date as well.
Git color coding for files in Intelli. J • • • 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.
Dealing with untracked files • Dragging a file into your project (not added to git automatically)
Viewing logs (same as log in Intelli. J) To see a log of all changes in your local repo: • $ git log or • $ git log --oneline (to show a shorter version) 1677 b 2 d Edited first line of readme 258 efa 7 Added line to readme 0 e 52 da 7 Initial commit • git log -5 (to show only the 5 most recent updates, etc. ) Note: changes will be listed by commit. ID #, (SHA-1 hash) Note: changes made to the remote repo before the last time you cloned/pulled from it will also be included here
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
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 1930 s 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 Big. Decimal. Main
Behavior Parameterization 100
How did Java deal with “functional” programming prior to Java 8 Urma/behavior. Param/_01 The. Problem. Defined
Another example of anon class
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
Another example
Another example
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 Java 7 and before are “functional interfaces” such as Runnable, Comparable, etc. • Java 8 defines many more functional interfaces in the java. util. function. * pacakge. • Older functional interfaces have been decorated with default methods to preserve backwards compatibility
Location of Functional Interfaces • You may define your own “Functional Interfaces” • Java 8 defines many in: java. util. function. * • 43 interfaces in 4 categories, such as Function, Supplier, Consumer, Predicate.
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, comp. L); • You may also use lambda expressions with Streams See functional. Iterface. Test
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 compileand run-time. • You can't use this keyword to identify it using reflection.
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. OO/lambdae xpressions. html Adib Saikali, Java 8 Lambda Expressions and Streams, www. youtube. com/watch? v=8 p. Dm_k. H 4 YKY Brian Goetz, Lambdas in Java: A peek under the hood. 111 https: //www. youtube. com/watch? v=MLksir. K 9 nn. E
Event-Source (Button) No Event-Listener listening Event (on. Click) No Catcher No Event Listener 112
Event-Source (Button) Event-Listener listening Event (on. Click) On. Click. Listener Any Object Catcher ready to catch 113
Behavior Parameterization Objects are first-class citizens in Java. You can now store references to functions. Functions too are first class citizens in Java. 114
The Lambda Calculus • • • The lambda calculus was introduced in the 1930 s 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. 115
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. 116
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. 2. x -> x * x 3. • (int x, int y) -> { return x + y; } ( ) -> 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. 117
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 118
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 119
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 120 binaries
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 121
Java 8 Lambdas • Syntax of Java 8 lambda expressions • Functional interfaces • Variable capture • Method references • Default methods 122
Example 1: Print a list of integers with a lambda List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(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 123
Example 2: A multiline lambda List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(x -> { x += 2; System. out. println(x); }); • Braces are needed to enclose a multiline body in a lambda 124 expression.
Example 3: A lambda with a defined local variable List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(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 125
Example 4: A lambda with a declared parameter type List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each((Integer x -> { x += 2; System. out. println(x); }); • You can, if you wish, specify the parameter type. 126
Functional Interfaces • • Design decision: Java 8 lambdas are assigned to functional interfaces. A functional interface is a Java interface with exactly one nondefault method. E. g. , public interface Consumer<T> { void accept(T t); } • The package java. util. function defines many new useful functional interfaces. 127
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 gen. Name(Integer x) { System. out. println(x); } Urma/behavior. Param/Using. Consumers. java 128
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. 129
Local Variable Capture Example public class LVCExample { public static void main(String[] args) { List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int var = 10; int. Seq. for. Each(x -> System. out. println(x + var)); } } 130
Static Variable Capture Example public class SVCExample { private static int var = 10; public static void main(String[] args) { List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(x -> System. out. println(x + var)); } } 131
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 132
Summary of Method References Method Reference Type Syntax Example static Class. Name: : Static. Method. Name String: : value. Of constructor Class. Name: : new Array. List: : new specific object instance object. Reference: : Method. Name x: : to. String arbitrary object of a given type Class. Name: : Instance. Method. Name Object: : to. String 133
Conciseness with Method References We can rewrite the statement int. Seq. for. Each(x -> System. out. println(x)); more concisely using a method reference int. Seq. for. Each(System. out: : println); 134
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=MLksir. K 9 nn. E 135
Streams
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<T> 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 Stream. Main
Iterator See Iterator. Driver
4 categories of Functional Interfaces Functional Interface archetypes Example used in Consumer for. Each(Consumer), peek(Consumer) Predicate filter(Predicate) Function map(Function) Supplier reduce(Supplier) collect(Supplier) See java. util. function. * Consumer. Main
4 categories of Functional Interfaces
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 string. Len. Comparator: : compare See Method. Refs. Main
Map is a transform • The. map() method is not an associative data structure, rather it is a transformative operation. It takes a Stream<T> and it returns either a Stream<T> or Stream<U>. • Example: Stream<String> to Stream<String> • Example: Stream<String> to Stream<Date>
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
Terminal operation • Terminal operation: A method that takes a Stream<T> and returns void. • They are eagerly loaded and will cause the entire pipeline to be executed. • A terminal operation will “spend” the stream. – The for. Each() method – The count() method – The max() method – The collect() method – The reduce() method
Slide references Lambdas: Alfred V. Aho ( http: //www. cs. columbia. edu/~aho/cs 6998/) 145
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<T> stream = collection. stream(); • • Streams can be sequential or parallel. Streams are useful for selecting values and performing actions on the results. 146
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. 147
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. 148
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 149
Stream Example int sum = widgets. stream(). filter(w -> w. get. Color() == RED). map. To. Int(w -> w. get. Weight()). sum(); Here, widgets is a Collection<Widget>. 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 From Java Docs stream of int values representing the weight of each red widget. 150 Interface Stream<T> Then this stream is summed to produce a total weight.
Parting Example: Using lambdas and stream to sum the squares of the elements on a list List<Integer> list = Arrays. as. List(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 http: //viralpatel. net/blogs/lambda-expressions-java-tutorial/ 151 then reduce((x, y) -> x + y) reduces all elements
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 152
d1683b495de3ca7c2a9ead1930cec64b.ppt