Download as pdf or txt
Download as pdf or txt
You are on page 1of 162

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY.

COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

D86513
May 2014
Edition 1.0
D80895GC10
Activity Guide
Java SE 8 New Features

Oracle University and CCYD S.R.L. use only


THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.

The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS

Oracle University and CCYD S.R.L. use only


The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.

Authors
Michael Williams, Tom McGinn, Nick Ristuccia

Technical Contributors and Reviewers


Stuart Marks, Staffan Friberg, Hiroshi Hiraga, Cindy Church, Erick Costlow

This book was published using: Oracle Tutor


THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Table of Contents
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-2
Practice 1-1: Log In to Oracle Linux ......................................................................................................... 1-3
Practice 1-2: Open Terminal Windows in Oracle Linux ............................................................................. 1-4
Practice 1-3: Add the Java bin Directory to the Path ................................................................................. 1-5
Practice 1-4: Open a Text File in Oracle Linux ......................................................................................... 1-6
Practice 1-5: Start NetBeans and Open a Project ..................................................................................... 1-7
Practices for Lesson 2: Lambda Introduction .......................................................................................... 2-1
Practices for Lesson 2: Lambda Introduction............................................................................................ 2-2
Practice 2-1: Lambda Syntax with an EventHandler ................................................................................. 2-3
Practice 2-2: Sort Collections with Comparator and Lambdas ................................................................... 2-4

Oracle University and CCYD S.R.L. use only


Practices for Lesson 3: A Case for Lambda Expressions........................................................................ 3-1
Practices for Lesson 3: Overview............................................................................................................. 3-2
Practice 3-1: Refactor Code to Use Lambda Expressions ......................................................................... 3-11
Practice 3-2: Refactor Code to Reuse Lambda Expressions ..................................................................... 3-12
Practices for Lesson 4: Filtering Collections with Lambdas ................................................................... 4-1
Practices for Lesson 4: Overview............................................................................................................. 4-2
Practice 4-1: Update RoboCall to use Streams......................................................................................... 4-5
Practice 4-2: Mail Sales Executives using Method Chaining ..................................................................... 4-6
Practice 4-3: Mail Sales Employees over 50 Using Method Chaining ........................................................ 4-7
Practice 4-4: Mail Male Engineering Employees Under 65 Using Method Chaining ................................... 4-8
Practices for Lesson 5: Using Built-in Lambda Types ............................................................................. 5-1
Practices for Lesson 5: Overview............................................................................................................. 5-2
Practice 5-1: Create Consumer Lambda Expression ................................................................................ 5-8
Practice 5-2: Create a Function Lambda Expression ................................................................................ 5-9
Practice 5-3: Create a Supplier Lambda Expression ................................................................................. 5-10
Practice 5-4: Create a BiPredicate Lambda Expression ............................................................................ 5-12
Practices for Lesson 6: Collection Operations with Lambda................................................................... 6-1
Practices for Lesson 6: Overview............................................................................................................. 6-2
Practice 6-1: Using Map and Peek ........................................................................................................... 6-16
Practice 6-2: FindFirst and Lazy Operations............................................................................................. 6-17
Practice 6-3: Analyze Transactions with Stream Methods ......................................................................... 6-19
Practice 6-4: Perform Calculations with Primitive Streams ........................................................................ 6-20
Practice 6-5: Sort Transactions with Comparator ...................................................................................... 6-21
Practice 6-6: Collect Results with Streams ............................................................................................... 6-23
Practice 6-7: Join Data with Streams ....................................................................................................... 6-24
Practice 6-8: Group Data with Streams .................................................................................................... 6-25
Practice 6-9: Partition Data with Streams ................................................................................................. 6-27
Practice 6-10: Calculate Sales Totals from Multiple Companies (Optional) ................................................ 6-28
Practices for Lesson 7: Parallel Streams ................................................................................................. 7-1
Practices for Lesson 7: Overview............................................................................................................. 7-2
Practice 7-1: Calculate Total Sales without a Pipeline............................................................................... 7-10
Practice 7-2: Calculate Sales Totals using Parallel Streams ..................................................................... 7-11
Practice 7-3: Calculate Sales Totals Using Parallel Streams and Reduce.................................................. 7-12
Practices for Lesson 8: Lambda Cookbook ............................................................................................. 8-1

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Java SE 8 New Features Table of Contents


iii
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 8: Overview............................................................................................................. 8-2


Practice 8-1: Working with ArrayLists....................................................................................................... 8-15
Practice 8-2: Working with Maps.............................................................................................................. 8-17
Practice 8-3: Working with Files ............................................................................................................... 8-18
Practice 8-4: Working with Directories...................................................................................................... 8-21
Practices for Lesson 9: Method Enhancements....................................................................................... 9-1
Practices for Lesson 9: Method Enhancements ........................................................................................ 9-2
Practice 9-1: Using Static Methods in Interfaces...................................................................................... 9-4
Practice 9-2: Using Static and Default Methods in Interfaces ................................................................... 9-5
Practices for Lesson 10: Using the Date/Time API - Working with Local Dates and Times .................... 10-1
Practices for Lesson 10 ........................................................................................................................... 10-2
Practice 10-1: Working with local dates and times .................................................................................... 10-3
Practices for Lesson 11 - Using the Date/Time API - Working with Time Zones ..................................... 11-1

Oracle University and CCYD S.R.L. use only


Practices for Lesson 11 ........................................................................................................................... 11-2
Practice 11-1: Working with Dates and Times Across Time Zones ............................................................ 11-3
Practices for Lesson 12 - Using the Date/Time API - Working with Date and Time Amounts ................. 12-1
Practices for Lesson 12 ........................................................................................................................... 12-2
Practice 12-1: Formatting Dates .............................................................................................................. 12-3
Practices for Lesson 13: Writing JavaScript with Java Using Nashorn - Creating and Executing
Shell Scripts.............................................................................................................................................. 13-1
Practices for Lesson 13 ........................................................................................................................... 13-2
Practice 13-1: Creating Shell Scripts Using Nashorn Global Objects ......................................................... 13-3
Practices for Lesson 14: Writing JavaScript with Java Using Nashorn - Writing JavaScript
Applications .............................................................................................................................................. 14-1
Practices for Lesson 14 ........................................................................................................................... 14-2
Practice 14-1: Creating a JavaScript Multi-Threaded Socket Server .......................................................... 14-3
Practices for Lesson 15: Writing JavaScript with Java Using Nashorn - Writing JavaFX Applications
Using JavaScript....................................................................................................................................... 15-1
Practices for Lesson 15 ........................................................................................................................... 15-2
Practice 15-1: Creating a JavaFX PieChart Application as a JavaScript Application................................... 15-3
Practice 15-2: Dynamically Changing a JavaFX Application...................................................................... 15-4
Practices for Lesson 16: Mission Control ................................................................................................ 16-1
Practices for Lesson 16: Overview ........................................................................................................... 16-2
Practice 16-1: The Mission Control General Page .................................................................................... 16-3
Practice 16-2: Mission Control MBeans Page........................................................................................... 16-5
Practice 16-3: Mission Control Triggers Tab............................................................................................. 16-7
Practice 16-4: Mission Control Other Tabs ............................................................................................... 16-9
Practices for Lesson 17: Java Flight Recorder ........................................................................................ 17-1
Practices for Lesson: Overview ............................................................................................................... 17-2
Practice 17-1: Starting a JFR Recording from Mission Control .................................................................. 17-3
Practice 17-2: Reviewing the Java Flight Recorder General Tab Group .................................................... 17-4
Practice 17-3: Reviewing the Java Flight Recorder Memory Tab Group .................................................... 17-5
Practice 17-4 Reviewing the Java Flight Recorder Code Tab Group ......................................................... 17-7

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Java SE 8 New Features Table of Contents


iv
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 1: Overview


Chapter 1 - Page 1
Chapter 1
Introduction

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.


Practices for Lesson 1:

Oracle University and CCYD S.R.L. use only


THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 1: Overview

Practice Overview
In these practices, you explore the systems and tools that are used throughout the remaining
practices.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Overview


Chapter 1 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-1: Log In to Oracle Linux

Overview
In this practice, you log in to the Oracle Linux operating system.

Assumptions
Oracle Linux 6 is installed on your system, and it is on and functioning.

Tasks
1. At the login screen, enter the following information:
User name: oracle
2. Click OK.

Oracle University and CCYD S.R.L. use only


Password: oracle
3. Click OK.

Root Access
Some of the utilities used in the practices require root system access. To obtain root access,
enter the following in a terminal window:
su
When prompted for the password, enter:
oracle

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-1: Log In to Oracle Linux


Chapter 1 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-2: Open Terminal Windows in Oracle Linux

Overview
In this practice, you open two terminal windows in Oracle Linux.

Assumptions
You are logged in to Oracle Linux, and you are running a Gnome Desktop.

Tasks
1. From the menu, select Applications > System Tools > Terminal.
A terminal session should start.
2. Repeat step 1 to open another terminal window.

Oracle University and CCYD S.R.L. use only


3. Alternatively, press Ctrl + Shift + T to open additional tabs in the same terminal window.
For Windows users: UNIX commands to use in your terminal window

DOS UNIX Description


dir ll list long (name, date, size, owner, etc)
ll -latr same as ll but sorted by date
dir/w ls list wide (no details)
dir/s locate find a file anywhere
del rm delete or remove files
copy cp copy file1 to file2
move mv move file1 to file2
ren mv rename file1 to file2
cd pwd print working directory
cd .. cd .. change directory UP one level
cd \ cd / change directory to TOP level (root)
C-A-D ps -ef process statistics (often used with grep)
top dynamic list of top processes by percent
md mkdir make directory
rd rmdir remove directory
edit vi full-screen character-based editor (see below)
more more list a file and pause (space/enter to continue)
tail -20 file1 list the last 20 lines of a file
type cat list a file and don't pause
strings same as cat but for files with binary chars
set set display all environment variables such as $HOME
help man manual (help) pages
find grep find a word in a line in a larger list of lines
prompt PS1='$PWD >' change the prompt to include current dir
logoff su - switch user (usually to Super User)
chkdsk df -k how much free space is left on disk
(n/a) which file1 finds executables along paths
ver uname –a version of operating system software

• Remember: Everything in UNIX is case-sensitive.


• To change to a ReallyLongDirectoryName, just type cd Rea*.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-2: Open Terminal Windows in Oracle Linux


Chapter 1 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-3: Add the Java bin Directory to the Path

Overview
In this practice, you open a terminal window and add the Java directory to the $PATH in Oracle
Linux.

Assumptions
You are logged in to Oracle Linux and you are running a Gnome Desktop.

Tasks
1. From the menu, select Applications > System Tools > Terminal.
2. A terminal session should start.

Oracle University and CCYD S.R.L. use only


3. At the command prompt, type:
gedit .bashrc
Note: This loads the bash configuration file.
4. Add the following line to the end of the file:
export PATH=/usr/java/jdk1.8.0/bin:/home/oracle/netbeans-
8.0/bin:$PATH:.
5. Save the file.
6. Close gedit.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-3: Add the Java bin Directory to the Path


Chapter 1 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-4: Open a Text File in Oracle Linux

Overview
In this practice, you open a text file by using the Nautilus file manager.

Assumptions
You are logged in to Oracle Linux and you are running a Gnome Desktop.

Tasks
1. Open the Nautilus file manager by double-clicking the Home folder on the desktop.
2. Double-click the labs directory to open it.
3. Double-click the read.txt file.

Oracle University and CCYD S.R.L. use only


The file is opened in the gedit text editor. Use Nautilus when you need to open a text file in
a practice.
4. Close the text file. Keep Nautilus running.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-4: Open a Text File in Oracle Linux


Chapter 1 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-5: Start NetBeans and Open a Project

Overview
In this practice, you launch NetBeans and open a NetBeans project.

Assumptions
NetBeans is installed and functioning correctly. You are logged in to Oracle Linux and you are
running Gnome Desktop.

Tasks
1. Open a terminal window.
2. At the command prompt, enter:

Oracle University and CCYD S.R.L. use only


netbeans &
3. The first time you run NetBeans, you may be prompted to register the product:

4. Just click Never Register and continue.


Note: The first time NetBeans runs, it caches and indexes a lot of information. Therefore,
the initial load time might be a little slow. Subsequent launches of the application will be
much faster.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-5: Start NetBeans and Open a Project


Chapter 1 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

After it launches, NetBeans should look like this:

Oracle University and CCYD S.R.L. use only


5. Open a sample NetBeans project by selecting File > Open Project.
6. Navigate to the labs/01Introduction/practices directory in your home directory.
7. Select the Java2D project and then click Open Project.
NetBeans should now look like this:

8. To run the project, right-click the project name and select Run.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-5: Start NetBeans and Open a Project


Chapter 1 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

9. Explore the user interface. Open some source files and other elements of the user
interface.
10. When you are done, right-click the project name and select Close.
11. Close NetBeans.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 1-5: Start NetBeans and Open a Project


Chapter 1 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 1-5: Start NetBeans and Open a Project


Chapter 1 - Page 10
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 2:
Lambda Introduction
Chapter 2

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Lambda Introduction


Chapter 2 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 2: Lambda Introduction

Practice Overview
In these practices, you explore how to use lambda expressions in place of functional interfaces.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Lambda Introduction


Chapter 2 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-1: Lambda Syntax with an EventHandler

Overview
In this practice, add multiple listeners to the example GUI app used in the lecture. When a
button is pushed, a message is displayed in the output window. Each listener should print a
different message and should be written using a different format.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/02LambdaIntro/practices/practice1 directory.

Tasks
1. Open the 01guiappPrac project in the practice1 directory.

Oracle University and CCYD S.R.L. use only


2. Open the source file for ClickTest.java.
3. Navigate to the comments that indicate where to replace anonymous inner classes with
lambda expressions.
4. The lambda expressions should be in the following sample formats. The anonymous inner
classes are already populated with print statements. Reuse those statements in your
lambda expressions.
a. Create a new lambda expression that specifies the variable type and prints an output
message using a code block, for example:
(ActionEvent e) -> {System.out.println("Message");}
b. Create a new lambda expression that infers the variable type and prints a message
using an expression, for example:
e -> System.out.println("Message")
c. Create a new listener with a lambda expression that infers the variable type and print a
multiline message using a code block and three print statements for example:
e -> {
System.out.println("Button 2 Message 1");
System.out.println("Message 2");
System.out.println("Message 3");
}
Output from the program should look similar to the following:
Button 1 2nd listner
Click detected by Anon Class
Button 2 Message 1
Message 2
Message 3
Test 2 button clicked
Note: When running JavaFX applications you may receive the following error message:
ES2 Prism: Error - reported GLX version = 1.2
GLX version 1.3 or higher is required
The error should not seriously affect your application. You can ignore the error.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 2-1: Lambda Syntax with an EventHandler


Chapter 2 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-2: Sort Collections with Comparator and Lambdas

Overview
In this practice, sort a collection using lambda expressions and the Comparator interface.

Comparator Review
Comparator is an interface that allows you to sort the elements in a collection. A typical
example of its use is shown in the following.

13 // Sort Asc
14 System.out.println("=== Sorted Asc SurName ===");
15 Collections.sort(personList, new Comparator<Person>() {
16 public int compare(Person p1, Person p2) {

Oracle University and CCYD S.R.L. use only


17 return p1.getSurName().compareTo(p2.getSurName());
18 }
19 });

So this piece of code takes a List of type Person and sorts it in ascending order based on the
surName field. Notice that this looks a lot like the ActionListener example in the previous
practice.
In fact, take a look at Comparator, can you identify a common pattern here?

3 public interface Comparator<T> {


4
5 int compare(T o1, T o2);
6
7 }

That's right, Comparator is a functional interface so the anonymous inner class can be
replaced with a lambda expression.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/02LambdaIntro/practices/practice2 directory.

Tasks
1. Open the 02compare project in the practice2 directory.
2. Review the Person.java file. Take a look at the fields and methods included with the
class.
3. Open ComparatorTest.java.
4. Replace the anonymous inner class comparator with a lambda expression.
5. Create a new lambda expression and re-sort the list in descending order.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 2-2: Sort Collections with Comparator and Lambdas


Chapter 2 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

The printed results should look something like this:

=== Sorted Asc SurName ===


Name: Joe Bailey
Name: Bob Baker
Name: Jane Doe
Name: John Doe
Name: James Johnson
Name: Betty Jones
Name: Phil Smith
=== Sorted Desc SurName ===
Name: Phil Smith

Oracle University and CCYD S.R.L. use only


Name: Betty Jones
Name: James Johnson
Name: Jane Doe
Name: John Doe
Name: Bob Baker
Name: Joe Bailey

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 2-2: Sort Collections with Comparator and Lambdas


Chapter 2 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-2: Sort Collections with Comparator and Lambdas


Chapter 2 - Page 6
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 3: A
Case for Lambda
Expressions
Chapter 3

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 3: Overview

Practice Overview
In these practices, you use lambda expressions to improve an application.

The RoboCall App


The RoboCall app is an application for automating the communication with groups of people.
The app can contact individuals by phone, email, or regular mail. In this example, the app will be
used to contact three groups of people.
• Drivers: Persons over the age of 16
• Draftees: Male persons between the ages of 18 and 25
• Pilots (specifically commercial pilots): Persons between the ages of 23 and 65

Oracle University and CCYD S.R.L. use only


Person
The Person class creates the master list of persons you want to contact. The class uses the
builder pattern to create new object. The following are some key parts of the class.
First, private fields for each Person are as follows:
Person.java
9 public class Person {
10 private String givenName;
11 private String surName;
12 private int age;
13 private Gender gender;
14 private String eMail;
15 private String phone;
16 private String address;
17 private String city;
18 private String state;
19 private String code;
20

So these will be the fields that our application can search.


A static method is used to create a list of sample users. The code looks something like this:
Person.java
167 public static List<Person> createShortList(){
168 List<Person> people = new ArrayList<>();
169
170 people.add(
171 new Person.Builder()
172 .givenName("Bob")
173 .surName("Baker")
174 .age(21)
175 .gender(Gender.MALE)
176 .email("bob.baker@example.com")
177 .phoneNumber("201-121-4678")
178 .address("44 4th St")
179 .city("Smallville")
180 .state("KS")
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

181 .code("12333")
182 .build()
183 );
184

The Initial RoboCall class


The following is the first attempt at a RoboCall class.
RoboCall01.java
11 public class RoboCall01 {
12
13 public void callDrivers(List<Person> pl){
14 for(Person p:pl){

Oracle University and CCYD S.R.L. use only


15 if (p.getAge() >= 16){
16 roboCall(p);
17 }
18 }
19 }
20
21 public void emailDraftees(List<Person> pl){
22 for(Person p:pl){
23 if (p.getAge() >= 18
24 && p.getAge() <= 25
25 && p.getGender() == Gender.MALE){
26
27 roboEmail(p);
28 }
29 }
30 }
31
32 public void mailPilots(List<Person> pl){
33 for(Person p:pl){
34 if (p.getAge() >= 23
35 && p.getAge() <= 65){
36
37 roboMail(p);
38 }
39 }
40 }
41
42 public void roboCall(Person p){
43 System.out.println("Calling " + p.getGivenName()
44 + " " + p.getSurName() + " age "
45 + p.getAge() + " at " + p.getPhone());
46 }
47
48 public void roboEmail(Person p){
49 System.out.println("EMailing " + p.getGivenName()
50 + " " + p.getSurName() + " age " + p.getAge()
51 + " at " + p.getEmail());
52 }
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

53
54 public void roboMail(Person p){
55 System.out.println("Mailing " + p.getGivenName()
56 + " " + p.getSurName() + " age " + p.getAge()
57 + " at " + p.getAddress() + ", " + p.getCity()
58 + ", " + p.getState() + " " + p.getCode());
59 }
60 }

Examining the method names shows that with this approach, a separate method would be
required for each communication type and group. Thus, nine methods are required to fully
complete the class. This would result in:
• A lot of redundant code

Oracle University and CCYD S.R.L. use only


• Any change in group rules would require quite a bit of maintenance work
So how can the code be improved?

RoboCall Take 2
To start, remove the group testing code from each method.
RoboCall02.java

9 public class RoboCall02 {


10
11 public void callDrivers(List<Person> pl){
12 for(Person p:pl){
13 if (isDriver(p)){
14 roboCall(p);
15 }
16 }
17 }
18
19 public void emailDraftees(List<Person> pl){
20 for(Person p:pl){
21 if (isDraftee(p)){
22 roboEmail(p);
23 }
24 }
25 }
26
27 public void mailPilots(List<Person> pl){
28 for(Person p:pl){
29 if (isPilot(p)){
30 roboMail(p);
31 }
32 }
33 }
34
35 public boolean isDriver(Person p){
36 return p.getAge() >= 16;
37 }
38
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

39 public boolean isDraftee(Person p){


40 return p.getAge() >= 18
41 && p.getAge() <= 25
42 && p.getGender() == Gender.MALE;
43 }
44
45 public boolean isPilot(Person p){
46 return p.getAge() >= 23 && p.getAge() <= 65;
47 }
48
49 public void roboCall(Person p){
50 System.out.println("Calling " + p.getGivenName()
51 + " " + p.getSurName() + " age " + p.getAge()
52 + " at " + p.getPhone());

Oracle University and CCYD S.R.L. use only


53 }
54
55 public void roboEmail(Person p){
56 System.out.println("EMailing " + p.getGivenName()
57 + " " + p.getSurName() + " age " + p.getAge()
58 + " at " + p.getEmail());
59 }
60
61 public void roboMail(Person p){
62 System.out.println("Mailing " + p.getGivenName()
63 + " " + p.getSurName() + " age " + p.getAge()
64 + " at " + p.getAddress() + ", " + p.getCity()
65 + ", " + p.getState() + " " + p.getCode());
66 }
67 }

Well this is an improvement to maintainability. Now if a change is made to group selection


criteria, the code only needs to be updated in three places. However, there is still a lot of
redundancy. Nine methods would still be required for each use case of groups and contact
methods. Plus, three methods have been added for the group tests.
What can be done to reduce the redundancy in the code?

RoboCall Take 3
One way to reduce redundancy would be to use anonymous inner classes. This can be
accomplished by writing an interface that performs the test and returns a boolean value. For
example:
MyTest.java
6 public interface MyTest<T> {
7 public boolean test(T t);
8 }

However, in Java 8 there are a number of pre-written functional interfaces for use with Lambda
expressions. One of these is the Predicate interface.
Predicate.java
1 package java.util.function;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

2
3 public interface Predicate<T> {
4 public boolean test(T t);
5 }

Since it is exactly the same except for the name, Predicate is used in the next code update.
Here is the updated RoboCall app with anonymous inner classes used as input to the
methods.
RoboCall03.java
10 public class RoboCall03 {
11
12 public void phoneContacts(
13 List<Person> pl, Predicate<Person> aTest){

Oracle University and CCYD S.R.L. use only


14
15 for(Person p:pl){
16 if (aTest.test(p)){
17 roboCall(p);
18 }
19 }
20 }
21
22 public void emailContacts(
23 List<Person> pl, Predicate<Person> aTest){
24
25 for(Person p:pl){
26 if (aTest.test(p)){
27 roboEmail(p);
28 }
29 }
30 }
31
32 public void mailContacts(
33 List<Person> pl, Predicate<Person> aTest){
34
35 for(Person p:pl){
36 if (aTest.test(p)){
37 roboMail(p);
38 }
39 }
40 }
41
42 public void roboCall(Person p){
43 System.out.println("Calling " + p.getGivenName()
44 + " " + p.getSurName() + " age " + p.getAge()
45 + " at " + p.getPhone());
46 }
47
48 public void roboEmail(Person p){
49 System.out.println("EMailing " + p.getGivenName()
50 + " " + p.getSurName() + " age " + p.getAge()
51 + " at " + p.getEmail());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

52 }
53
54 public void roboMail(Person p){
55 System.out.println("Mailing " + p.getGivenName()
56 + " " + p.getSurName() + " age " + p.getAge()
57 + " at " + p.getAddress() + ", " + p.getCity()
58 + ", " + p.getState() + " " + p.getCode());
59 }
60
61 }

At first glance, this looks a lot better. Instead of the 12 methods from before, only three methods
are required, one for each communication method. But how is this accomplished? It looks like
some sort of class or interface is passed into each method. A deeper investigation is required.

Oracle University and CCYD S.R.L. use only


What about the test class that calls RoboCall? What does the code look like?
RoboCallTest03.java
9 public class RoboCallTest03 {
10
11 public static void main(String[] args) {
12
13 List<Person> pl = Person.createShortList();
14 RoboCall03 robo = new RoboCall03();
15
16 System.out.println("\n==== Robo Test 03");
17 System.out.println("\n=== Calling all Drivers");
18 robo.phoneContacts(pl,
19 new Predicate<Person>(){
20 @Override
21 public boolean test(Person p){
22 return p.getAge() >=16;
23 }
24 }
25 );
26
27 System.out.println("\n=== Emailing all Draftees");
28 robo.emailContacts(pl,
29 new Predicate<Person>(){
30 @Override
31 public boolean test(Person p){
32 return p.getAge() >= 18
33 && p.getAge() <= 25
34 && p.getGender() == Gender.MALE;
35 }
36 }
37 );

Well, it looks like all that has been done is the redundancy problem has just been shifted
someplace else. In addition, this is a great example of the vertical problem. An anonymous inner
class is required each time one of the communication methods is called.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

So for each use case, a separate inner class must be rewritten. The maintenance problem
solved in take 2 is now back. Any change in the selection criteria would force a rewrite of any
code that called the method.
So is there a better way to do this? Maybe lambda expressions can help.

RoboCall with Lambda Expressions


Here is the updated RoboCall with lambda expressions.
RoboCall04.java
10 public class RoboCall04 {
11
12 public void phoneContacts(
13 List<Person> pl, Predicate<Person> aTest){
14

Oracle University and CCYD S.R.L. use only


15 for(Person p:pl){
16 if (aTest.test(p)){
17 roboCall(p);
18 }
19 }
20 }
21
22 public void emailContacts(
23 List<Person> pl, Predicate<Person> aTest){
24
25 for(Person p:pl){
26 if (aTest.test(p)){
27 roboEmail(p);
28 }
29 }
30 }
31
32 public void mailContacts(
33 List<Person> pl, Predicate<Person> aTest){
34
35 for(Person p:pl){
36 if (aTest.test(p)){
37 roboMail(p);
38 }
39 }
40 }
41
42 public void roboCall(Person p){
43 System.out.println("Calling " + p.getGivenName()
44 + " " + p.getSurName() + " age " + p.getAge()
45 + " at " + p.getPhone());
46 }
47
48 public void roboEmail(Person p){
49 System.out.println("EMailing " + p.getGivenName()
50 + " " + p.getSurName() + " age " + p.getAge()
51 + " at " + p.getEmail());
52 }

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

53
54 public void roboMail(Person p){
55 System.out.println("Mailing " + p.getGivenName()
56 + " " + p.getSurName() + " age " + p.getAge()
57 + " at " + p.getAddress() + ", " + p.getCity()
58 + ", " + p.getState() + " " + p.getCode());
59 }
60
61 }
So the RoboCall class is pretty much the same. In fact, it is exactly the same. What about the
test class? Does that change?
RoboCallTest04.java
8 public class RoboCallTest04 {

Oracle University and CCYD S.R.L. use only


9
10 public static void main(String[] args) {
11
12 List<Person> pl = Person.createShortList();
13 RoboCall04 robo = new RoboCall04();
14
15 System.out.println("\n==== Robo Test 04");
16 System.out.println("\n=== Calling all Drivers");
17 robo.phoneContacts(pl,
18 (Person p) -> p.getAge() >=16);
19
20 System.out.println("\n=== Emailing all Draftees");
21 robo.emailContacts(pl,
22 p -> p.getAge() >= 18 && p.getAge() <= 25
23 && p.getGender() == Gender.MALE);
24
25
26 System.out.println("\n=== Mail all Pilots");
27 robo.mailContacts(pl,
28 p -> p.getAge() >= 23 && p.getAge() <= 65);
This code looks a lot simpler and cleaner than the anonymous inner class example. Notice on
lines 18, 22, and 28 the selection criteria is specified with a lambda expression. Definitely, it is a
big improvement.
There is one last change worth looking at. This code is cleaner and easier to read, but notice
that each lambda expression must be repeated for drivers, draftees, and pilots. Can this be
fixed?
RoboCallTest05.java
10 public class RoboCallTest05 {
11
12 public static void main(String[] args){
13
14 List<Person> pl = Person.createShortList();
15 RoboCall05 robo = new RoboCall05();
16
17 // Predicates
18 Predicate<Person> allDrivers =
19 p -> p.getAge() >= 16;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

20
21 Predicate<Person> allDraftees =
22 p -> p.getAge() >= 18
23 && p.getAge() <= 25
24 && p.getGender() == Gender.MALE;
25
26 Predicate<Person> allPilots =
27 p -> p.getAge() >= 23 && p.getAge() <= 65;
28
29
30 System.out.println("\n==== Robo Test 05");
31 System.out.println("\n=== Calling all Drivers");
32 robo.phoneContacts(pl, allDrivers);
33

Oracle University and CCYD S.R.L. use only


34 System.out.println("\n=== Emailing all Draftees");
35 robo.emailContacts(pl, allDraftees);
36
37 System.out.println("\n=== Mail all Pilots");
38 robo.mailContacts(pl, allPilots);
39
40 }
41 }

The expression can be assigned to an interface type (Predicate<Person> in this case) and
stored in a variable and reused. In this case, the lambda type is explicitly assigned and then
passed to the action methods using allDrivers, allDraftees, and allPilots.
All lambda expressions have a type, whether it is assigned to a variable or passed as a
parameter like RoboCallTest04.java. The type of lambda is targeted based on the context it
is used. Because the methods are expecting a Predicate<Person>, this is the type assigned
to the expression. This is known as target typing. Target typing can be used in a number of
contexts including:
• Variable declarations
• Assignments
• Return statements
• Array initializers
• Method or constructor arguments
• Lambda expression bodies
• Conditional expressions
• Cast expressions

Summary so Far
So the code has been improved quite a bit so far. The code is much cleaner and less
redundant. The lambda expression clearly expresses that the selection criteria is without the
cruft associated with an inner class. Plus, expressions can be stored and reused any time.
However, one thing remains that needs to be changed. How do we improve the for loops for
processing our lists? Is there a way to select elements without processing the entire list every
time? These questions are answered in the lesson titled “Filtering Collections with Lambdas”.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Overview


Chapter 3 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-1: Refactor Code to Use Lambda Expressions

Overview
In this practice, you have been given an old email mailing list program named RoboMail. It is
used to send emails or text messages to employees at your company. Refactor RoboMail so it
uses lambda expressions instead of anonymous inner classes.

Assumptions
You have completed the lecture and reviewed the overview for this practice.

Tasks
1. Open the EmployeeSearch03-01prac project in the practice01 directory for this
lesson.

Oracle University and CCYD S.R.L. use only


2. Open the Employee.java file and become familiar with the code included in the file.
3. Open the RoboMailOldStyle.java file and review the code in the file.
4. Open the RoboTest01.java file and review the code there.
5. Run the project and examine the output.
6. Update the RoboMailTest01.java file and replace the anonymous inner classes with
lambda expressions.
7. Your program should perform the following tasks to the following groups.
• Email all HR employees: e.getDept().equals("HR")
• Text all sales employees: e.getDept().equals("Sales")
• Text all sales executives: e.getRole().equals(Role.EXECUTIVE) &&
e.getDept().equals("Sales")
• Email all sales older than 50: e.getAge() >= 50 &&
e.getDept().equals("Sales")
Your output should look similar to the following:
==== RoboMail 01

=== Members of HR ===


Emailing: John Doe age 28 at john.doe@example.com
Emailing: Phil Smith age 55 at phil.smith@examp;e.com

=== All Sales ===


Texting: Jane Doe age 25 at 202-123-4678
Texting: John Adams age 52 at 112-111-1111
Texting: Betty Jones age 65 at 211-333-1234

=== All Sales Execs


Texting: Betty Jones age 65 at 211-333-1234

=== All Sales 50+


Emailing: John Adams age 52 at john.adams@example.com
Emailing: Betty Jones age 65 at betty.jones@example.com

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 3-1: Refactor Code to Use Lambda Expressions


Chapter 3 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-2: Refactor Code to Reuse Lambda Expressions

Overview
In this practice, continue with the previous project or use the project provided in the following.

Assumptions
You have completed the lecture and completed the previous practice.

Tasks
1. Open the EmployeeSearch03-02prac project in the practice02 directory for this
lesson.
2. Open the RoboMailTest01.java file and review the code there.

Oracle University and CCYD S.R.L. use only


3. Update the RoboMailTest01.java file to store lambda expressions in variables.
a. Create a variable salesExecutives that stores a lambda expression that selects all
sales employees: e.getDept().equals("Sales")
b. Create a variable salesEmployeesOver50 that stores a lambda expression that
selects sales employees over the age of 50: e.getAge() >= 50 &&
e.getDept().equals("Sales")
4. Your program should perform the following tasks to the following groups.
• Email all sales executives
• Text all sales executives
• Email all sales employees older than 50
• Text all sales employees older than 50

Your output should look similar to the following:


==== RoboMail 01

=== Sales Execs ===


Emailing: Betty Jones age 65 at betty.jones@example.com
Texting: Betty Jones age 65 at 211-33-1234

=== All Sales ===


Emailing: John Adams age 52 at john.adams@example.com
Emailing: Betty Jones age 65 at betty.jones@example.com
Texting: John Adams age 52 at 112-111-1111
Texting: Betty Jones age 65 at 211-33-1234

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 3-2: Refactor Code to Reuse Lambda Expressions


Chapter 3 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 4:
Filtering Collections with
Lambdas
Chapter 4

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Overview


Chapter 4 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 4: Overview

Practice Overview
In these practices, update the practices from the previous lesson to use forEach, streams,
pipelines, and the filter method to display query results.

forEach
All collections have a new forEach method.
RoboCallTest06.java
9 public class RoboCallTest06 {
10

Oracle University and CCYD S.R.L. use only


11 public static void main(String[] args){
12
13 List<Person> pl = Person.createShortList();
14
15 System.out.println("\n=== Print List ===");
16 pl.forEach(p -> System.out.println(p));
17
18 }
19 }

Notice that the forEach takes a method reference or a lambda expression as a parameter. In
the example, the toString method is called to print out each Person object. Some form of
expression is needed to specify the output.

Stream and Filter


The following example shows how a stream() and filter() method are used with a
collection in the RoboCall app.
RoboCallTest07.java
10 public class RoboCallTest07 {
11
12 public static void main(String[] args){
13
14 List<Person> pl = Person.createShortList();
15 RoboCall05 robo = new RoboCall05();
16
17 System.out.println("\n=== Calling all Drivers Lambda ===");
18 pl.stream()
19 .filter(p -> p.getAge() >= 23 && p.getAge() <= 65)
20 .forEach(p -> robo.roboCall(p));
21
22 }
23 }

The stream method creates a pipeline of immutable Person elements and access to methods
that can perform actions on those elements. The filter method takes a lambda expression as

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Overview


Chapter 4 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

a parameter and filters on the logical expression provide. This indicates that a Predicate is
the target type of the filter. The elements that meet the filter criteria are passed to the forEach
method, which does a roboCall on matching elements.
The following example is functionally equivalent to the last. But in the case, the lambda
expression is assigned to a variable, which is then passed to the stream and filter.
RoboCallTest08.java
10 public class RoboCallTest08 {
11
12 public static void main(String[] args){
13
14 List<Person> pl = Person.createShortList();
15 RoboCall05 robo = new RoboCall05();
16

Oracle University and CCYD S.R.L. use only


17 // Predicates
18 Predicate<Person> allPilots =
19 p -> p.getAge() >= 23 && p.getAge() <= 65;
20
21 System.out.println("\n=== Calling all Drivers Variable ===");
22 pl.stream().filter(allPilots)
23 .forEach(p -> robo.roboCall(p));
24 }
25 }

Method References
In cases where a lambda expression just calls an instance method, a method reference can be
used instead.
A03aMethodReference.java
9 public class A03aMethodReference {
10
11 public static void main(String[] args) {
12
13 List<SalesTxn> tList = SalesTxn.createTxnList();
14
15 System.out.println("\n== CA Transations Lambda ==");
16 tList.stream()
17 .filter(t -> t.getState().equals("CA"))
18 .forEach(t -> t.printSummary());
19
20 tList.stream()
21 .filter(t -> t.getState().equals("CA"))
22 .forEach(SalesTxn::printSummary);
23 }
24 }
So lines 18 and 22 are essentially equivalent. Method reference syntax uses the class name
followed by "::" and then the method name.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Overview


Chapter 4 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Chaining and Pipelines


The final example compares a compound lambda statement with a chained version using
multiple filter methods.
A04IterationTest.java
9 public class A04IterationTest {
10
11 public static void main(String[] args) {
12
13 List<SalesTxn> tList = SalesTxn.createTxnList();
14
15 System.out.println("\n== CA Transations for ACME ==");
16 tList.stream()
17 .filter(t -> t.getState().equals("CA") &&
18 t.getBuyerName().equals("Acme Electronics"))

Oracle University and CCYD S.R.L. use only


19 .forEach(SalesTxn::printSummary);
20
21 tList.stream()
22 .filter(t -> t.getState().equals("CA"))
23 .filter(t -> t.getBuyerName()
24 .equals("Acme Electronics"))
25 .forEach(SalesTxn::printSummary);
26 }
27 }

The two examples are essentially equivalent. The second example demonstrates how methods
can be chained to possibly make the code a little easier to read. Both are examples of pipelines
created by the stream method.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Overview


Chapter 4 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-1: Update RoboCall to use Streams

Overview
In this practice, continue to work with the RoboMail app from the previous lesson.

Assumptions
You have completed the lecture and completed the previous lesson and practices for that
lesson.

Tasks
1. Open the EmployeeSearch04-01prac project in the practice01 directory for this
lesson.
2. Open the RoboMail01.java file and remove the mail and text methods. They are no

Oracle University and CCYD S.R.L. use only


longer needed since a stream will be used to filter the employees and a forEach will call
the required communication task.
3. Open the RoboMailTest01.java file and review the code there.
4. Update RoboMailTest01.java to use stream, filter, and forEach to perform the
mailing and texting tasks of the previous program.
5. Your program should continue to perform the following tasks to the following groups.
• Email all sales executives using stream, filter, and forEach.
• Text all sales executives using stream, filter, and forEach.
• Email all sales employees older than 50 using stream, filter, and forEach.
• Text all sales employees older than 50 using stream, filter, and forEach.
6. To mail or text a group in the forEach method, use a lambda expression for each task.
a. Mail example: p -> robo.roboMail(p)
b. Text example: p -> robo.roboText(p)
Your output should look similar to the following:
==== RoboMail 01

=== Sales Execs


Emailing: Betty Jones age 65 at betty.jones@example.com
Texting: Betty Jones age 65 at 211-33-1234

=== All Sales


Emailing: John Adams age 52 at john.adams@example.com
Emailing: Betty Jones age 65 at betty.jones@example.com
Texting: John Adams age 52 at 112-111-1111
Texting: Betty Jones age 65 at 211-33-1234

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 4-1: Update RoboCall to use Streams


Chapter 4 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-2: Mail Sales Executives using Method Chaining

Overview
In this practice, continue to work with the RoboMail app from the previous lesson.

Assumptions
You have completed the lecture and completed the previous practice.

Tasks
1. Open the EmployeeSearch04-02prac project in the practice02 directory for this
lesson.
2. Open the RoboMailTest01.java file and review the code there.

Oracle University and CCYD S.R.L. use only


3. Update the RoboMailTest01.java file to mail all sales executives. Use two filter
methods to select the recipients of the mail.
The output from the program should look similar to the following:
==== RoboMail 01

=== Sales Execs


Emailing: Betty Jones age 65 at betty.jones@example.com

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 4-2: Mail Sales Executives using Method Chaining


Chapter 4 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-3: Mail Sales Employees over 50 Using Method Chaining

Overview
In this practice, continue to work with the RoboMail app from the previous lesson.

Assumptions
You have completed the lecture and completed the previous practice.

Tasks
1. Open the EmployeeSearch04-03prac project in the practice03 directory for this
lesson.
2. Open the RoboMailTest01.java file and review the code there.

Oracle University and CCYD S.R.L. use only


3. Update the RoboMailTest01.java file to mail all sales employees over 50. Use two filter
methods to select the recipients of the mail.
The output from the program should look similar to the following:
==== RoboMail 01

=== All Sales 50+


Emailing: John Adams age 52 at john.adams@example.com
Emailing: Betty Jones age 65 at betty.jones@example.com

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 4-3: Mail Sales Employees over 50 Using Method Chaining


Chapter 4 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-4: Mail Male Engineering Employees Under 65 Using


Method Chaining

Overview
In this practice, continue to work with the RoboMail app from the previous lesson.

Assumptions
You have completed the lecture and completed the previous practice.

Tasks
1. Open the EmployeeSearch04-04prac project in the practice04 directory for this
lesson.

Oracle University and CCYD S.R.L. use only


2. Open the RoboMailTest01.java file and review the code there.
3. Update the RoboMailTest01.java file to mail all male engineering employees under 65.
Use three filter methods to select the recipients of the mail.
The output from the program should look similar to the following:
==== RoboMail 01

=== Male Eng Under 65


Emailing: James Johnson age 45 at james.johnson@example.com
Emailing: Joe Bailey age 62 at joebob.bailey@example.com

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 4-4: Mail Male Engineering Employees Under 65 Using Method Chaining
Chapter 4 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 5: Using
Built-in Lambda Types
Chapter 5

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 5: Overview

Practice Overview
In these practices, create lambda expressions using the built-in functional interfaces found in
the java.util.function package.
The focus of this lesson and examples is to make you familiar with the built-in functional
interfaces for use with lambda expressions. They are often used as parameters for method calls
with streams. Familiarity with these interfaces makes working with streams much easier.

Predicate
The Predicate interface has already been covered in the last lesson. Essentially, it is a
lambda expression that takes a generic type and returns a boolean.
A01Predicate.java

Oracle University and CCYD S.R.L. use only


10 public class A01Predicate {
11
12 public static void main(String[] args){
13
14 List<SalesTxn> tList = SalesTxn.createTxnList();
15
16 Predicate<SalesTxn> massSales =
17 t -> t.getState().equals(State.MA);
18
19 System.out.println("\n== Sales - Stream");
20 tList.stream()
21 .filter(massSales)
22 .forEach(t -> t.printSummary());
23
24 System.out.println("\n== Sales - Method Call");
25 for(SalesTxn t:tList){
26 if (massSales.test(t)){
27 t.printSummary();
28 }
29 }
30 }
31 }
In the preceding code, the lambda expression is used in a filter for a stream. The second
example also shows that the test method can be executed on any SalesTxn element using
the functional interface that stores the Predicate.
To repeat, a Predicate takes in a generic type and returns a boolean.

Consumer
The Consumer interface specifies a generic type but returns nothing. Essentially, it is a void
return type for lambdas. In the following example, the lambda expression specifies how a
transaction should be printed.
A02Consumer.java
10 public class A02Consumer {
11
12 public static void main(String[] args){
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

13
14 List<SalesTxn> tList = SalesTxn.createTxnList();
15 SalesTxn first = tList.get(0);
16
17 Consumer<SalesTxn> buyerConsumer = t ->
18 System.out.println("Id: " + t.getTxnId()
19 + " Buyer: " + t.getBuyerName());
20
21 System.out.println("== Buyers - Lambda");
22 tList.stream().forEach(buyerConsumer);
23
24 System.out.println("== First Buyer - Method");
25 buyerConsumer.accept(first);
26 }

Oracle University and CCYD S.R.L. use only


27 }
For the forEach method, the default argument is a Consumer. The lambda expression is
basically just a print statement that is used in the two cases shown. In the second example, the
accept method is called along with a transaction. This prints the first transaction in the list.
The key point here is that the Consumer takes a generic type and returns nothing. It is
essentially a void return type for lambda expressions.

Function
The Function interface specifies two generic object types to be used in the expression. The
first generic object is used in the lambda expression and the second is the return type from the
lambda expression. The example uses a SalesTxn to return a String.
A03Function.java
10 public class A03Function {
11
12 public static void main(String[] args){
13
14 List<SalesTxn> tList = SalesTxn.createTxnList();
15 SalesTxn first = tList.get(0);
16
17 Function<SalesTxn, String> buyerFunction =
18 t -> t.getBuyerName();
19
20 System.out.println("\n== First Buyer");
21 System.out.println(buyerFunction.apply(first));
The Function has one method named apply. In this example, a String is returned to the
print statement.
With a Function the key concept is that a Function takes in one type and returns another.

Supplier
The Supplier interface specifies one generic type, which is returned from the lambda
expression. Nothing is passed in so this is similar to a Factory. The follow expression example
creates and returns a SalesTxn and adds it to our existing list.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A04Supplier.java
13 public static void main(String[] args){
14
15 List<SalesTxn> tList = SalesTxn.createTxnList();
16 Supplier<SalesTxn> txnSupplier =
17 () -> new SalesTxn.Builder()
18 .txnId(101)
19 .salesPerson("John Adams")
20 .buyer(Buyer.getBuyerMap().get("PriceCo"))
21 .product("Widget")
22 .paymentType("Cash")
23 .unitPrice(20)
24 .unitCount(8000)
25 .txnDate(LocalDate.of(2013,11,10))

Oracle University and CCYD S.R.L. use only


26 .city("Boston")
27 .state(State.MA)
28 .code("02108")
29 .build();
30
31 tList.add(txnSupplier.get());
32 System.out.println("\n== TList");
33 tList.stream().forEach(SalesTxn::printSummary);
34 }
Notice a Supplier has no input arguments, there is merely empty parentheses: () ->. The
example uses a builder to create a new object. Notice Supplier has only one method get, which
in this case returns a SalesTxn.
The key take away with a Supplier is that it has no input parameters but returns a generic
type.
So that pretty much covers the basic function interfaces. However, there are a lot of variations.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Primitive Types - ToDoubleFunction and AutoBoxing


There are primitive versions of all the built-in lambda functional interfaces. The following code
shows an example of the ToDoubleFunction interface.
A05PrimFunction.java
11 public class A05PrimFunction {
12
13 public static void main(String[] args){
14
15 List<SalesTxn> tList = SalesTxn.createTxnList();
16 SalesTxn first = tList.get(0);
17
18 ToDoubleFunction<SalesTxn> discountFunction =
19 t -> t.getTransactionTotal()

Oracle University and CCYD S.R.L. use only


20 * t.getDiscountRate();
21
22 System.out.println("\n== Discount");
23 System.out.println(
24 discountFunction.applyAsDouble(first));
25
Remember a Function takes in one generic and return a different generic. However, the
ToDoubleFunction interface has only one generic specified. That is because it takes a
generic type as input and returns a double. Notice also that the method name for this
functional interface is applyAsDouble. So to repeat, the ToDoubleFunction takes in a
generic and returns a double. There are also long and int versions of this interface.
Why create these primitive variations? Consider this piece of code.
A05PrimFunction.java
26 // What's wrong here?
27 Function<SalesTxn, Double> taxFunction =
28 t -> t.getTransactionTotal() * t.getTaxRate();
29 double tax = taxFunction.apply(first); // What happerns here?
30 }
31 }
With object types, this would require the autoboxing and unboxing of primitive values. Not good
for performance. These specialized primitive interfaces address this issue and allow for
operations on primitive types.

Primitive Types -– DoubleFunction


What if you need to pass in a primitive to a lambda expression? Well, the DoubleFunction
interface is a great example of that.
A06DoubleFunction.java
5 public class A06DoubleFunction {
6
7 public static void main(String[] args) {
8
9 A06DoubleFunction test = new A06DoubleFunction();
10
11 DoubleFunction<String> calc =
12 t -> String.valueOf(t * 3);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

13
14 String result = calc.apply(20);
15 System.out.println("New value is: " + result);
16 }
17 }
Primitive interfaces like DoubleFunction, IntFunction, or LongFunction take a primitive
as input and return a generic type. In this case, a double is passed to the lambda expression
and a String is returned. Once again, this avoids any boxing issues.

Binary Intefaces – BiPredicate


A number of examples having the Predicate interface have been explored so far in this
course. A Predicate takes a generic class and returns a boolean. But what if you want to
compare two things? There is a binary specialization for that.

Oracle University and CCYD S.R.L. use only


The BiPredicate interface allows two object types to be used in a lambda expression. Binary
interfaces for the other main interface types are also available.
A07Binary.java
10 public class A07Binary {
11
12 public static void main(String[] args){
13
14 List<SalesTxn> tList = SalesTxn.createTxnList();
15 SalesTxn first = tList.get(0);
16 String testState = "CA";
17
18 BiPredicate<SalesTxn,String> stateBiPred =
19 (t, s) -> t.getState().equals(State.CA);
20
21 System.out.println("\n== First in CA?");
22 System.out.println(
23 stateBiPred.test(first, testState));
24 }
25 }
The example specifies a SalesTxn and a String as the generic types used in the lambda
expression. Note that the types are specified with t and s and a boolean is still returned. It is
the same result as a Predicate, but with two input types.

UnaryOperator
The Function interface takes in one generic and returns a different generic. What if you want
to return the same thing? Then the UnaryOperator interface is what you need.
A08Unary.java
10 public class A08Unary {
11
12 public static void main(String[] args){
13
14 List<SalesTxn> tList = SalesTxn.createTxnList();
15 SalesTxn first = tList.get(0);
16
17 UnaryOperator<String> unaryStr =
18 s -> s.toUpperCase();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

19
20 System.out.println("== Upper Buyer");
21 System.out.println(
22 unaryStr.apply(first.getBuyerName()));
23 }
24 }
The example takes a String and returns an uppercase version of that String.

API Docs
As a reminder, it is difficult to remember all the variations of functional interfaces and what they
do. Make liberal use of the API docs to remember your options or what is returned for the
java.util.function package.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Overview


Chapter 5 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Create Consumer Lambda Expression

Overview
In this practice, create a Consumer lambda expression to print out employee data.
Note that salary and startDate fields were added to the Employee class. In addition,
enumerations are included for Bonus and VacAccrual. The enums allow calculations for
bonuses and vacation time.

Assumptions
You have completed the lecture portion of the course.

Tasks
1. Open the EmployeeSearch05-01Prac project in the practice1 directory for this

Oracle University and CCYD S.R.L. use only


lesson.
2. Open the Employee.java file and become familiar with the code included in the file.
3. Open the ConsumerTest.java file and make the following updates.
4. Write a Consumer lambda expression to print data about the first employee in the list.
a. The data printed should be the following: "Name: " + e.getSurName() + "
Role: " + e.getRole() + " Salary: " + e.getSalary()
5. Write a statement to execute the lambda expression on the first variable.
6. Your output should look similar to the following:
=== First Salary
Name: Baker Role: STAFF Salary: 40000.0

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 5-1: Create Consumer Lambda Expression


Chapter 5 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Create a Function Lambda Expression

Overview
In this practice, create a ToDoubleFunction lambda expression to calculate an employee
bonus.

Assumptions
You have completed the lecture portion of the course and the previous practice.

Tasks
1. Open the EmployeeSearch05-02Prac project in the practice2 directory for this
lesson.

Oracle University and CCYD S.R.L. use only


2. Open the Bonus.java file and review the code included in the file.
3. Open the FunctionTest.java file and make the following updates.
4. Write a ToDoubleFunction lambda expression to calculate the bonus for the first
employee in the list.
a. The bonus can be calculated as follows: e.getSalary() *
Bonus.byRole(e.getRole())
5. Write a statement to execute the lambda expression on the first variable.
6. Your output should look similar to the following:
=== First Employee Bonus
Name: Bob Baker Role: STAFF Dept: ENG eMail: bob.baker@example.com
Salary: 40000.0
Bonus: 800.0

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 5-2: Create a Function Lambda Expression


Chapter 5 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-3: Create a Supplier Lambda Expression

Overview
In this practice, create a Supplier lambda expression to add a new employee to the employee
list.

Assumptions
You have completed the lecture portion of the course and the previous practice.

Tasks
1. Open the EmployeeSearch05-03Prac project in the practice3 directory for this
lesson.

Oracle University and CCYD S.R.L. use only


2. Open the SupplierTest.java file and make the following updates.
3. Write a Supplier lambda expression to add a new employee to the list. The employee
data is as follows:
Given name: Jill
SurName: Doe
Age: 26
Gender: Gender.FEMALE
Role: Role.STAFF
Dept: Sales
StartDate: LocalDate.of(2012, 7, 14)
Salary: 45000
Email: jill.doe@example.com
PhoneNumber: 202-123-4678
Address: 33 3rd St
City: Smallville
State: KS
Code: 12333
Hint: Her data is almost exactly the same as her sister Jane and can be found in the
Employee.java file.
4. Write a statement to add the new employee to the employee list.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 5-3: Create a Supplier Lambda Expression


Chapter 5 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

5. Your output should look similar to the following after adding the new employee to the list:
=== Print employee list after
Name: Bob Baker Role: STAFF Dept: ENG eMail: bob.baker@example.com
Salary: 40000.0
Name: Jane Doe Role: STAFF Dept: Sales eMail: jane.doe@example.com
Salary: 45000.0
Name: John Doe Role: MANAGER Dept: Eng eMail: john.doe@example.com
Salary: 65000.0
Name: James Johnson Role: MANAGER Dept: Eng eMail:
james.johnson@example.com Salary: 85000.0
Name: John Adams Role: MANAGER Dept: Sales eMail:
john.adams@example.com Salary: 90000.0
Name: Joe Bailey Role: EXECUTIVE Dept: Eng eMail:
joebob.bailey@example.com Salary: 120000.0

Oracle University and CCYD S.R.L. use only


Name: Phil Smith Role: EXECUTIVE Dept: HR eMail:
phil.smith@examp;e.com Salary: 110000.0
Name: Betty Jones Role: EXECUTIVE Dept: Sales eMail:
betty.jones@example.com Salary: 140000.0
Name: Jill Doe Role: STAFF Dept: Sales eMail: jill.doe@example.com
Salary: 45000.0

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 5-3: Create a Supplier Lambda Expression


Chapter 5 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-4: Create a BiPredicate Lambda Expression

Overview
In this practice, create a BiPredicate lambda expression to calculate an employee bonus.

Assumptions
You have completed the lecture portion of the course and the previous practice.

Tasks
1. Open the EmployeeSearch05-04Prac project in the practice4 directory for this
lesson.
2. Open the BiPredicateTest.java file and make the following updates.

Oracle University and CCYD S.R.L. use only


3. Write a BiPredicate lambda expression to compare a field in the employee class to a
string.
a. The searchState variable should be compared to the state value in the employee
element.
4. Write an expression to perform the logical test in the for loop.
5. Your output should look similar to the following:
=== Print matching list
Name: Bob Baker Role: STAFF Dept: ENG eMail: bob.baker@example.com
Salary: 40000.0
Name: Jane Doe Role: STAFF Dept: Sales eMail: jane.doe@example.com
Salary: 45000.0
Name: John Doe Role: MANAGER Dept: Eng eMail: john.doe@example.com
Salary: 65000.0

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 5-4: Create a BiPredicate Lambda Expression


Chapter 5 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 6:
Collection Operations with
Lambda
Chapter 6

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 6: Overview

Practice Overview
In these practices, you explore the various operations you can perform on a collection with the
lambda expressions and streams.

Employee List
Here is a short list of Employees and their data that will be used for the examples that follow.
Name: Bob Baker Role: STAFF Dept: Eng St: KS Salary: $40,000.00
Name: Jane Doe Role: STAFF Dept: Sales St: KS Salary: $45,000.00
Name: John Doe Role: MANAGER Dept: Eng St: KS Salary: $65,000.00
Name: James Johnson Role: MANAGER Dept: Eng St: MA Salary: $85,000.00
Name: John Adams Role: MANAGER Dept: Sales St: MA Salary: $90,000.00
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00

Oracle University and CCYD S.R.L. use only


Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00

Map
The map method in the Stream class allows you to extract a field from a stream and perform
some operation or calculation on that value. The resulting values are then passed to the next
stream in the pipeline.
A01MapTest.java
9 public class A01MapTest {
10
11 public static void main(String[] args) {
12
13 List<Employee> eList = Employee.createShortList();
14
15 System.out.println("\n== CO Bonuses ==");
16 eList.stream()
17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .filter(e -> e.getState().equals("CO"))
19 .map(e -> e.getSalary() * Bonus.byRole(e.getRole()))
20 .forEach( s -> System.out.printf("Bonus paid: $%,6.2f %n", s));
21

The example prints out the bonuses for two different groups. The filter methods select the
groups and then map is used to compute a result.
Output
== CO Bonuses ==
Bonus paid: $7,200.00
Bonus paid: $6,600.00
Bonus paid: $8,400.00

Peek
The peek method of the Stream class allows you to perform an operation on an element in the
stream. The elements are returned to the stream and are available to the next stream in the
pipeline. The peek method can be used to read or change data in the stream. Any changes will
be made to the underlying collection.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A02MapPeekTest.java
15 System.out.println("\n== CO Bonuses ==");
16 eList.stream()
17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .filter(e -> e.getState().equals("CO"))
19 .peek(e -> System.out.print("Name: "
20 + e.getGivenName() + " " + e.getSurName()))
21 .map(e -> e.getSalary() * Bonus.byRole(e.getRole()))
22 .forEach( s ->
23 System.out.printf(
24 " Bonus paid: $%,6.2f %n", s));

In this example, after filtering the data, peek is used to print data from the current stream to the
console. After the map method is called, only the data returned from map is available for output.

Oracle University and CCYD S.R.L. use only


Output
== CO Bonuses ==
Name: Joe Bailey Bonus paid: $7,200.00
Name: Phil Smith Bonus paid: $6,600.00
Name: Betty Jones Bonus paid: $8,400.00

Find First
The findFirst method of the Stream class finds the first element in the stream specified by
the filters in the pipeline. The findFirst method is a terminal short-circuit operation. This
means intermediate operations are performed in a lazy manner resulting in more efficient
processing of the data in the stream. A terminal operation ends the processing of a pipeline.
A03FindFirst.java
10 public class A03FindFirst {
11
12 public static void main(String[] args) {
13
14 List<Employee> eList = Employee.createShortList();
15
16 System.out.println("\n== First CO Bonus ==");
17 Optional<Employee> result;
18
19 result = eList.stream()
20 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
21 .filter(e -> e.getState().equals("CO"))
22 .findFirst();
23
24 if (result.isPresent()){
25 result.get().print();
26 }
27
28 }
The code filters the pipeline for executives in the state of Colorado. The first element in the
collection that meets this criterion is returned and printed out. Notice that the type of the result

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

variable is Optional<Employee>. This is a new class that allows you to determine if a value is
present before trying to retrieve a result. This has advantages for concurrent applications.
Output
== First CO Bonus ==

Name: Joe Bailey


Age: 62
Gender: MALE
Role: EXECUTIVE
Dept: Eng
Start date: 1992-01-05
Salary: 120000.0
eMail: joebob.bailey@example.com
Phone: 112-111-1111

Oracle University and CCYD S.R.L. use only


Address: 111 1st St
City: Town
State: CO
Code: 11111

Find First Lazy


The following example compares a pipeline, which filters and iterates through an entire
collection to a pipeline with a short-circuit terminal operation (findFirst). The peek method is
used to print out a message associated with each operation.
A04FindFirstLazy.java
10 public class A04FindFirstLazy {
11
12 public static void main(String[] args) {
13
14 List<Employee> eList = Employee.createShortList();
15
16 System.out.println("\n== CO Bonuses ==");
17 eList.stream()
18 .peek(e -> System.out.println("Stream start"))
19 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
20 .peek(e -> System.out.println("Executives"))
21 .filter(e -> e.getState().equals("CO"))
22 .peek(e -> System.out.println("CO Executives"))
23 .map(e -> e.getSalary() * Bonus.byRole(e.getRole()))
24 .forEach( s -> System.out.printf(
25 " Bonus paid: $%,6.2f %n", s));
26
27 System.out.println("\n== First CO Bonus ==");
28 Employee tempEmp = new Employee.Builder().build();
29 Optional<Employee> result = eList.stream()
30 .peek(e -> System.out.println("Stream start"))
31 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
32 .peek(e -> System.out.println("Executives"))
33 .filter(e -> e.getState().equals("CO"))
34 .peek(e -> System.out.println("CO Executives"))

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

35 .findFirst();
36
37 if (result.isPresent()){
38 result.get().printSummary();
39 }
40 }
41 }
The pipeline prints out 17 different options. The second, with a short-circuit operator, prints 8.
This demonstrates how lazy operations can really improve the performance of iteration through
a collection.
Output
== CO Bonuses ==
Stream start

Oracle University and CCYD S.R.L. use only


Stream start
Stream start
Stream start
Stream start
Stream start
Executives
CO Executives
Bonus paid: $7,200.00
Stream start
Executives
CO Executives
Bonus paid: $6,600.00
Stream start
Executives
CO Executives
Bonus paid: $8,400.00

== First CO Bonus ==
Stream start
Stream start
Stream start
Stream start
Stream start
Stream start
Executives
CO Executives
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary:
$120,000.00

anyMatch
The anyMatch method returns a boolean based on the specified Predicate. This is a short-
circuiting terminal operation.
A05AnyMatch.java
10 public class A05AnyMatch {
11
12 public static void main(String[] args) {
13
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

14 List<Employee> eList = Employee.createShortList();


15
16 System.out.println("\n== First CO Bonus ==");
17 Optional<Employee> result;
18
19 if (eList.stream().anyMatch(
20 e -> e.getState().equals("CO"))){
21
22 result = eList.stream()
23 .peek(e -> System.out.println("Stream"))
24 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
25 .filter(e -> e.getState().equals("CO"))
26 .findFirst();
27

Oracle University and CCYD S.R.L. use only


28 if (result.isPresent()){result.get().printSummary();}
29 }
The example shows how the anyMatch method could be used to check for a value before
executing a more detailed query.

Count
The count method returns the number of elements in the current stream. This is a terminal
operation.
A06StreamData.java
15 List<Employee> eList = Employee.createShortList();
16
17 System.out.println("\n== Executive Count ==");
18 long execCount =
19 eList.stream()
20 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
21 .count();
22
23 System.out.println("Exec count: " + execCount);
The example returns the number of executives in Colorado and prints the result.
Output
== Executive Count ==
Exec count: 3

Max
The max method returns the highest matching value given a Comparator to rank elements.
The max method is a terminal operation.
A06StreamData.java
23 System.out.println("Exec count: " + execCount);
24
25 System.out.println("\n== Highest Paid Exec ==");
26 Optional highestExec =
27 eList.stream()
28 .filter(e -> e.getRole().equals(Role.EXECUTIVE))

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

29 .max(Employee::sortBySalary);
30
31 if (highestExec.isPresent()){
32 Employee temp = (Employee) highestExec.get();
33 System.out.printf(
34 "Name: " + temp.getGivenName() + " "
35 + temp.getSurName() + " Salary: $%,6.2f %n ",
36 temp.getSalary());
37 }
The example shows max being used with a Comparator that has been written for the class.
The sortBySalary method is called using a method reference. Notice the return type of
Optional. This is not the generic version used in previous examples. Therefore, a cast is
required when the object is retrieved.

Oracle University and CCYD S.R.L. use only


Output
== Highest Paid Exec ==
Name: Betty Jones Salary: $140,000.00

Min
The min method returns the lowest matching value given a Comparator to rank elements. The
min method is a terminal operation.
A06StreamData.java
39 System.out.println("\n== Lowest Paid Staff ==");
40 Optional lowestStaff =
41 eList.stream()
42 .filter(e -> e.getRole().equals(Role.STAFF))
43 .min(Comparator.comparingDouble(e -> e.getSalary()));
44
45 if (lowestStaff.isPresent()){
46 Employee temp = (Employee) lowestStaff.get();
47 System.out.printf("Name: " + temp.getGivenName()
48 + " " + temp.getSurName() +
49 " Salary: $%,6.2f %n ", temp.getSalary());
50 }
In this example a different Comparator is used. The comparingDouble static method is
called to make the comparison. Notice that the example uses a lambda expression to specify
the comparison field. If you look at the code closely, a method reference could be substituted
instead: Employee::getSalary. More discussion on this subject follows in the Comparator
section.
Output
== Lowest Paid Staff ==
Name: Bob Baker Salary: $40,000.00

Sum
The sum method calculates a sum based on the stream passed to it. Notice the mapToDouble
method is called before the stream is passed to sum. If you look at the Stream class, no sum

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

method is included. Instead, a sum method is included in the primitive version of the Stream
class, IntStream, DoubleStream, and LongStream. The sum method is a terminal
operation.
A07CalcSum.java
26 System.out.println("\n== Total CO Bonus Details ==");
27
28 result = eList.stream()
29 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
30 .filter(e -> e.getState().equals("CO"))
31 .peek(e -> System.out.print("Name: "
32 + e.getGivenName() + " " + e.getSurName() + " "))
33 .mapToDouble(e -> e.getSalary() * Bonus.byRole(e.getRole()))
34 .peek(d -> System.out.printf("Bonus paid: $%,6.2f %n", d))
35 .sum();

Oracle University and CCYD S.R.L. use only


36
37 System.out.printf("Total Bonuses paid: $%,6.2f %n", result);
Looking at the example, can you tell the type of result? If the API documentation is examined,
the mapToDouble method returns a DoubleStream. The sum method for DoubleStream
returns a double. Therefore, the result variable must be a double.
Output
== Total CO Bonus Details ==
Name: Joe Bailey Bonus paid: $7,200.00
Name: Phil Smith Bonus paid: $6,600.00
Name: Betty Jones Bonus paid: $8,400.00
Total Bonuses paid: $22,200.00

Average
The average method returns the average of a list of values passed from a stream. The avg
method is a terminal operation.
A08CalcAvg.java
28 System.out.println("\n== Average CO Bonus Details ==");
29
30 result = eList.stream()
31 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
32 .filter(e -> e.getState().equals("CO"))
33 .peek(e -> System.out.print("Name: " + e.getGivenName()
34 + " " + e.getSurName() + " "))
35 .mapToDouble(e -> e.getSalary() * Bonus.byRole(e.getRole()))
36 .peek(d -> System.out.printf("Bonus paid: $%,6.2f %n", d))
37 .average();
38
39 if (result.isPresent()){
40 System.out.printf("Average Bonuses paid: $%,6.2f %n",
41 result.getAsDouble());
42 }
43 }

Once again, the return type for avg can be inferred from the code shown in this example. Note
the check for isPresent() in the if statement and the call to getAsDouble(). In this case an
OptionalDouble is returned.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Output
== Average CO Bonus Details ==
Name: Joe Bailey Bonus paid: $7,200.00
Name: Phil Smith Bonus paid: $6,600.00
Name: Betty Jones Bonus paid: $8,400.00
Average Bonuses paid: $7,400.00

Sorted
The sorted method can be used to sort stream elements based on their natural order. This is an
intermediate operation.
A09SortBonus.java
10 public class A09SortBonus {

Oracle University and CCYD S.R.L. use only


11 public static void main(String[] args) {
12 List<Employee> eList = Employee.createShortList();
13
14 System.out.println("\n== CO Bonus Details ==");
15
16 eList.stream()
17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .filter(e -> e.getState().equals("CO"))
19 .mapToDouble(e -> e.getSalary() * Bonus.byRole(e.getRole()))
20 .sorted()
21 .forEach(d -> System.out.printf("Bonus paid: $%,6.2f %n", d));
In this example, the bonus is computed and those values are used to sort the results. So a list
for double values is sorted and printed out.
Output
== CO Bonus Details ==
Bonus paid: $6,600.00
Bonus paid: $7,200.00
Bonus paid: $8,400.00

Sorted with Comparator


The sorted method can also take a Comparator as a parameter. Combined with the
comparing method, the Comparator class provides a great deal of flexibility when sorting a
stream.
A10SortComparator.java
11 public class A10SortComparator {
12 public static void main(String[] args) {
13 List<Employee> eList = Employee.createShortList();
14
15 System.out.println("\n== CO Bonus Details Comparator ==");
16
17 eList.stream()
18 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
19 .filter(e -> e.getState().equals("CO"))
20 .sorted(Comparator.comparing(Employee::getSurName))
21 .forEach(Employee::printSummary);

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

In this example, notice on line 20 that a method reference is passed to the comparing method.
In this case, the stream is sorted by surname. However, clearly the implication is any of the get
methods from the Employee class could be passed to this method. So with one simple
expression, a stream can be sorted by any available field.
Output
== CO Bonus Details Comparator ==
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00

Reversed
The reversed method can be appended to the comparing method thus reversing the sort

Oracle University and CCYD S.R.L. use only


order of the elements in the stream. The example and output demonstrate this using surname.
A10SortComparator.java
23 System.out.println("\n== CO Bonus Details Reversed ==");
24
25 eList.stream()
26 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
27 .filter(e -> e.getState().equals("CO"))
28 .sorted(Comparator.comparing(Employee::getSurName).reversed())
29 .forEach(Employee::printSummary);
Output
== CO Bonus Details Reversed ==
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00

Two Level Sort


In this example, the thenComparing method has been added to the comparing method. This
allows you to do a multilevel sort on the elements in the stream. The thenComparing method
takes a Comparator as a parameter just like the comparing method.
A10SortComparator.java
31 System.out.println("\n== Two Level Sort, Dept then Surname ==");
32
33 eList.stream()
34 .sorted(
35 Comparator.comparing(Employee::getDept)
36 .thenComparing(Employee::getSurName))
37 .forEach(Employee::printSummary);
In the example, the stream is sorted by department and then by surname. The output is as
follows.
Output
== Two Level Sort, Dept then Surname ==
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Bob Baker Role: STAFF Dept: Eng St: KS Salary: $40,000.00
Name: John Doe Role: MANAGER Dept: Eng St: KS Salary: $65,000.00
Name: James Johnson Role: MANAGER Dept: Eng St: MA Salary: $85,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00


Name: John Adams Role: MANAGER Dept: Sales St: MA Salary: $90,000.00
Name: Jane Doe Role: STAFF Dept: Sales St: KS Salary: $45,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00

Collect
The collect method allows you to save the results of all the filtering, mapping, and sorting
that takes place in a pipeline. Notice how the collect method is called. It takes a
Collectors class as a parameter. The Collectors class provides a number of ways to
return the elements left in a pipeline.
A11Collection.java
12 public class A11Collect {

Oracle University and CCYD S.R.L. use only


13
14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 List<Employee> nList = new ArrayList<>();
19
20 // Collect CO Executives
21 nList = eList.stream()
22 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
23 .filter(e -> e.getState().equals("CO"))
24 .sorted(Comparator.comparing(Employee::getSurName))
25 .collect(Collectors.toList());
26
27 System.out.println("\n== CO Bonus Details ==");
28
29 nList.stream()
30 .forEach(Employee::printSummary);
31
32 }
33
34 }
In this example, the Collectors class simply returns a new List, which consists of the
elements selected by the filter methods. In addition to a List, a Set or a Map may be returned
as well. Plus there are a number of other options for save the pipeline results. Below are the
three Employee elements that match the filter criteria in sorted order.
Output
== CO Bonus Details ==
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00

Collectors and Math


The Collectors class includes a number of math methods including averagingDouble and
summingDouble along with other primitive versions.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A12CollectMath.java
12 public class A12CollectMath {
13
14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 // Collect CO Executives
19 double avgSalary = eList.stream()
20 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
21 .filter(e -> e.getState().equals("CO"))
22 .collect(
23 Collectors.averagingDouble(Employee::getSalary));
24

Oracle University and CCYD S.R.L. use only


25 System.out.println("\n== CO Exec Avg Salary ==");
26 System.out.printf("Average: $%,9.2f %n", avgSalary);
27
28 }
29
30 }
In this example, an average salary is computed for based on the filters provided. A double
primitive value is returned.
Output
== CO Exec Avg Salary ==
Average: $123,333.33

Collectors and Joining


The joining method of the Collectors class allows you to join together elements returned
from a stream.
A13CollectJoin.java
12 public class A13CollectJoin {
13
14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 // Collect CO Executives
19 String deptList = eList.stream()
20 .map(Employee::getDept)
21 .distinct()
22 .collect(Collectors.joining(", "));
23
24 System.out.println("\n== Dept List ==");
25 System.out.println("Total: " + deptList);
26
27 }
28
29 }

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

In this example, the values for department are extracted from the stream using a map. A call is
made to the distinct method, which removes any duplicate values. The resulting values are
joined together using the joining method. The output is shown in the following.
Output
== Dept List ==
Total: Eng, Sales, HR

Collectors and Grouping


The groupingBy method of the Collectors class allows you to generate a Map based on the
elements contained in a stream.
A14CollectGrouping.java

Oracle University and CCYD S.R.L. use only


12 public class A14CollectGrouping {
13
14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 Map<String, List<Employee>> gMap = new HashMap<>();
19
20 // Collect CO Executives
21 gMap = eList.stream()
22 .collect(Collectors.groupingBy(Employee::getDept));
23
24 System.out.println("\n== Employees by Dept ==");
25 gMap.forEach((k,v) -> {
26 System.out.println("\nDept: " + k);
27 v.forEach(Employee::printSummary);
28 });
29
30 }
31
32 }
In this example, the groupingBy method is called with a method reference to getDept. This
created a Map with the department names used as key and a list of elements that match that
key become the value for the Map. Notice how the Map is specified on line 18. In addition,
starting on line 25 the code iterates through the resulting Map. The output from the Map is
shown in the following.
Output
== Employees by Dept ==

Dept: Sales
Name: Jane Doe Role: STAFF Dept: Sales St: KS Salary: $45,000.00
Name: John Adams Role: MANAGER Dept: Sales St: MA Salary: $90,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00

Dept: HR
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00

Dept: Eng
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 13
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Name: Bob Baker Role: STAFF Dept: Eng St: KS Salary: $40,000.00
Name: John Doe Role: MANAGER Dept: Eng St: KS Salary: $65,000.00
Name: James Johnson Role: MANAGER Dept: Eng St: MA Salary: $85,000.00
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00

Collectors, Grouping, and Counting


Another version of the groupingBy function takes a Function and Collector as
parameters and returns a Map. This example builds on the last and instead of returning
matching elements, it counts them.
A15CollectCount.java
12 public class A15CollectCount {
13

Oracle University and CCYD S.R.L. use only


14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 Map<String, Long> gMap = new HashMap<>();
19
20 // Collect CO Executives
21 gMap = eList.stream()
22 .collect(
23 Collectors.groupingBy(
24 e -> e.getDept(), Collectors.counting()));
25
26 System.out.println("\n== Employees by Dept ==");
27 gMap.forEach((k,v) ->
28 System.out.println("Dept: " + k + " Count: " + v)
29 );
30
31 }
32
33 }
Note how the method once again creates the Map based on department. But this time,
Collectors.counting is used to return long values to the Map. The output from the Map is
shown in the following.
Output
== Employees by Dept ==
Dept: Sales Count: 3
Dept: HR Count: 1
Dept: Eng Count: 4

Collectors and Partitioning


The partitioningBy method offers an interesting way to create a Map. The method takes a
Predicate as an argument and creates a Map with two Boolean keys. One key is true and
includes all the elements that met the true criteria of the Predicate. The other key, false,
contains all the elements that resulted in false values as determined by the Predicate.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 14
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A16CollectPartition.java
12 public class A16CollectPartition {
13
14 public static void main(String[] args) {
15
16 List<Employee> eList = Employee.createShortList();
17
18 Map<Boolean, List<Employee>> gMap = new HashMap<>();
19
20 // Collect CO Executives
21 gMap = eList.stream()
22 .collect(
23 Collectors.partitioningBy(
24 e -> e.getRole().equals(Role.EXECUTIVE)));

Oracle University and CCYD S.R.L. use only


25
26 System.out.println("\n== Employees by Dept ==");
27 gMap.forEach((k,v) -> {
28 System.out.println("\nGroup: " + k);
29 v.forEach(Employee::printSummary);
30 });
31
32 }
33
34 }
This example creates a Map based on role. All executives will be in the true group, and all
other employees will be in the false group. Here is a printout of the map.
Output
== Employees by Dept ==

Group: false
Name: Bob Baker Role: STAFF Dept: Eng St: KS Salary: $40,000.00
Name: Jane Doe Role: STAFF Dept: Sales St: KS Salary: $45,000.00
Name: John Doe Role: MANAGER Dept: Eng St: KS Salary: $65,000.00
Name: James Johnson Role: MANAGER Dept: Eng St: MA Salary: $85,000.00
Name: John Adams Role: MANAGER Dept: Sales St: MA Salary: $90,000.00

Group: true
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Overview


Chapter 6 - Page 15
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-1: Using Map and Peek

Overview
In this practice, use lambda expressions and the stream method along with the map and peek
methods to print a report on all the Widget Pro sales in the state of California (CA).

Assumptions
You have completed the lecture portion of this course.

Tasks
1. Open the SalesTxn06-01Prac project in the practice01 directory for this lesson.
2. Review the code for the SalesTxn class. Note that enumerations exist for BuyerClass,
State, and TaxRate.

Oracle University and CCYD S.R.L. use only


3. Modify the MapTest class to create a sales tax report.
a. Filter the transactions for the following.
− Transactions from the state of CA: t.getState().equals(State.CA)
− Transactions for the Widget Pro product:
t.getProduct().equals("Widget Pro")
b. Use the map method to calculate the sales tax. The calculation is as follows:
t.getTransactionTotal() * TaxRate.byState(t.getState())
c. Print a report similar to the following:
=== Widget Pro Sales Tax in CA ===
Txn tax: $36,000.00
Txn tax: $180,000.00
Note: To get the comma-separated currency, use something like this:
System.out.printf("Txn tax: $%,9.2f%n", amt)
5. Copy the main method from the MapTest class to the PeekTest class.
6. Update your code to print more detailed information about the matching transaction using
the peek method. A Consumer is provided for you that adds the following:
 Transaction ID
 Buyer
 Total Transaction amount
 Sales tax amount
7. The output should look similar to the following:
=== Widget Pro Sales Tax in CA ===
Id: 12 Buyer: Acme Electronics Txn amt: $400,000.00 Txn tax:
$36,000.00
Id: 13 Buyer: Radio Hut Txn amt: $2,000,000.00 Txn tax: $180,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-1: Using Map and Peek


Chapter 6 - Page 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-2: FindFirst and Lazy Operations

Overview
In this practice, compare a forEach loop to a findFirst short-circuit terminal operation and
see how the two differ in number of operations.
The following Consumer lambda expressions have been written for you to save you from some
typing. The variables are: quantReport, streamStart, stateSearch, and
productSearch.

Assumptions
You have completed the lecture portion of the lesson and the previous practice.

Tasks

Oracle University and CCYD S.R.L. use only


1. Open the SalesTxn06-02Prac project in the practice02 directory for this lesson.
2. Edit the LazyTest class to perform the steps in this practice.
3. Using stream and lambda expressions print out a list of transactions that meet the
following criteria.
a. Create a filter to select all "Widget Pro" sales.
b. Create a filter to select transactions in the state of Colorado (CO).
c. Iterate through the matching transactions and print a report similar to the following
using quantReport in the forEach.
=== Widget Pro Quantity in CO ===
Seller: Betty Jones-- Buyer: Radio Hut -- Quantity: 20,000
Seller: Dave Smith-- Buyer: PriceCo -- Quantity: 6,000
Seller: Betty Jones-- Buyer: Best Deals -- Quantity: 20,000
4. Perform the same search as in the previous step. This time use the peek method to display
each step in the process. Put a peek method call in the following places.
a. Add a peek method after the stream() method that uses the streamStart as its
parameter.
b. Add a peek method after the filter for state that uses stateSearch as its
parameter.
c. Add a peek method after the filter for product that uses productSearch as its
parameter.
d. Print the final result using forEach as in the previous step.
e. The output should look similar to the following.
=== Widget Pro Quantity in CO ===
Stream start: Jane Doe ID: 11
Stream start: Jane Doe ID: 12
Stream start: Jane Doe ID: 13
Stream start: John Smith ID: 14
Stream start: Betty Jones ID: 15
State Search: Betty Jones St: CO
Product Search
Seller: Betty Jones-- Buyer: Radio Hut -- Quantity: 20,000
Stream start: Betty Jones ID: 16
State Search: Betty Jones St: CO
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-2: FindFirst and Lazy Operations


Chapter 6 - Page 17
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Stream start: Dave Smith ID: 17


State Search: Dave Smith St: CO
Product Search
Seller: Dave Smith-- Buyer: PriceCo -- Quantity: 6,000
Stream start: Dave Smith ID: 18
State Search: Dave Smith St: CO
Stream start: Betty Jones ID: 19
State Search: Betty Jones St: CO
Product Search
Seller: Betty Jones-- Buyer: Best Deals -- Quantity: 20,000
Stream start: John Adams ID: 20
Stream start: John Adams ID: 21
Stream start: Samuel Adams ID: 22
Stream start: Samuel Adams ID: 23

Oracle University and CCYD S.R.L. use only


Stream start: Samuel Adams ID: 24
5. Copy the code from the previous step so you can modify it.
6. Replace the forEach with a findFirst method.
7. Add the following code:
f. Use an Optional<SalesTxn> named ft to store the result.
g. Write an if statement to check to see if ft.isPresent().
h. If a value is returned, call the accept method of quantReport to display the result.
i. Your output should look similar to the following:
=== Widget Pro Quantity in CO (FindFirst)===
Stream start: Jane Doe ID: 11
Stream start: Jane Doe ID: 12
Stream start: Jane Doe ID: 13
Stream start: John Smith ID: 14
Stream start: Betty Jones ID: 15
State Search: Betty Jones St: CO
Product Search
Seller: Betty Jones-- Buyer: Radio Hut -- Quantity: 20,000
Take a moment to consider the difference between terminal and short-circuit terminal
operations.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-2: FindFirst and Lazy Operations


Chapter 6 - Page 18
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-3: Analyze Transactions with Stream Methods

Overview
In this practice, count the number of transactions and determine the min and max values in the
collection for transactions involving Radio Hut.

Assumptions
You have completed the lecture portion of this lesson and the last practice.

Tasks
1. Open the SalesTx06-03Prac project in the practice03 directory for this lesson.
2. Edit the RadioHutTest class to perform the steps in this practice.

Oracle University and CCYD S.R.L. use only


3. Using stream and lambda expressions print out all the transactions involving Radio Hut.
a. Use a filter to select all "Radio Hut" transactions.
b. Use the radioReport variable to print the matching transactions.
c. Your output should look similar to the following:
=== Radio Hut Transactions ===
ID: 13 Seller: Jane Doe-- Buyer: Radio Hut -- State: CA -- Amt:
$2,000,000
ID: 15 Seller: Betty Jones-- Buyer: Radio Hut -- State: CO -- Amt:
$ 800,000
ID: 23 Seller: Samuel Adams-- Buyer: Radio Hut -- State: MA -- Amt:
$1,040,000
4. Use stream, filter, and lambda expressions to calculate and print out the total number
of transactions involving Radio Hut. (Hint: Use the count method.)
5. Use stream and lambda expressions to calculate and print out the largest transaction
based on the total transaction amount involving Radio Hut. Use the max function with a
Comparator, for example:
.max(Comparator.comparing(SalesTxn::getTransactionTotal))
6. Using stream and lambda expressions calculate and print out the smallest transaction
based on the total transaction amount involving Radio Hut. Use the min method in a
manner similar to the previous method.
Hint: Remember to check the API documentation for the return types for the specified
methods.
7. When complete, your output should look similar to the following.
=== Radio Hut Transactions ===
ID: 13 Seller: Jane Doe-- Buyer: Radio Hut -- State: CA -- Amt: $2,000,000
ID: 15 Seller: Betty Jones-- Buyer: Radio Hut -- State: CO -- Amt: $ 800,000
ID: 23 Seller: Samuel Adams-- Buyer: Radio Hut -- State: MA -- Amt: $1,040,000
Total Transactions: 3
=== Radio Hut Largest ===
ID: 13 Seller: Jane Doe-- Buyer: Radio Hut -- State: CA -- Amt: $2,000,000
=== Radio Hut Smallest ===
ID: 15 Seller: Betty Jones-- Buyer: Radio Hut -- State: CO -- Amt: $ 800,000

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-3: Analyze Transactions with Stream Methods


Chapter 6 - Page 19
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-4: Perform Calculations with Primitive Streams

Overview
In this practice, calculate the sales totals and average units sold from the collection of sales
transactions.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-04Prac project in the practice04 directory for this lesson.
2. Edit the CalcTest class to perform the steps in this practice.

Oracle University and CCYD S.R.L. use only


3. Calculate the total sales for "Radio Hut", "PriceCo", and "Best Deals" and print the results.
 For example, filter Radio Hut with a lambda like this:
t -> t.getBuyerName().equals("Radio Hut")
 For example, get the transaction total with:
.mapToDouble( t -> t.getTransactionTotal())
4. Calculate the average number of units sold for the "Widget" and "Widget Pro" products and
print the results.
 For example, the Widget Pro code looks like the following:
.filter(t -> t.getProduct().equals("Widget Pro"))
.mapToDouble( t-> t.getUnitCount())
Hint: Be mindful of the method return types. Use to the API doc to ensure you are using the
correct methods and classes to create and store results.
5. The output from your test class should be similar to the following:
=== Transactions Totals ===
Radio Hut Total: $3,840,000.00
PriceCo Total: $1,460,000.00
Best Deals Total: $1,300,000.00
=== Average Unit Count ===
Widget Pro Avg: 21,143
Widget Avg: 12,400

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-4: Perform Calculations with Primitive Streams


Chapter 6 - Page 20
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-5: Sort Transactions with Comparator

Overview
In this practice, sort transactions using the Comparator class, the comparing method, and
the sorted method.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-05Prac project in the practice05 directory for this lesson.
2. Edit the SortTest class to perform the steps in this practice.

Oracle University and CCYD S.R.L. use only


3. Use streams and lambda expressions to print out all the PriceCo transactions by
transaction total in ascending order.
 The sorted method should look something like this:
.sorted(Comparator.comparing(SalesTxn::getTransactionTotal))
 Use the transReport variable to print the results.
4. Use the same data from the previous step to print out the PriceCo transactions in
descending order.
5. Print out all the transactions sorted using the following sort keys.
 Buyer name
 Sales person
 Transaction total
6. When complete, the output should look similar to the following:
=== PriceCo Transactions ===
Id: 17 Seller: Dave Smith Buyer: PriceCo Amt: $240,000.00
Id: 20 Seller: John Adams Buyer: PriceCo Amt: $280,000.00
Id: 18 Seller: Dave Smith Buyer: PriceCo Amt: $300,000.00
Id: 21 Seller: John Adams Buyer: PriceCo Amt: $640,000.00

=== PriceCo Transactions Reversed ===


Id: 21 Seller: John Adams Buyer: PriceCo Amt: $640,000.00
Id: 18 Seller: Dave Smith Buyer: PriceCo Amt: $300,000.00
Id: 20 Seller: John Adams Buyer: PriceCo Amt: $280,000.00
Id: 17 Seller: Dave Smith Buyer: PriceCo Amt: $240,000.00

=== Triple Sort Transactions ===


Id: 11 Seller: Jane Doe Buyer: Acme Electronics Amt: $60,000.00
Id: 12 Seller: Jane Doe Buyer: Acme Electronics Amt: $400,000.00
Id: 16 Seller: Betty Jones Buyer: Best Deals Amt: $500,000.00
Id: 19 Seller: Betty Jones Buyer: Best Deals Amt: $800,000.00
Id: 14 Seller: John Smith Buyer: Great Deals Amt: $100,000.00
Id: 22 Seller: Samuel Adams Buyer: Mom and Pops Amt: $60,000.00
Id: 17 Seller: Dave Smith Buyer: PriceCo Amt: $240,000.00
Id: 18 Seller: Dave Smith Buyer: PriceCo Amt: $300,000.00
Id: 20 Seller: John Adams Buyer: PriceCo Amt: $280,000.00
Id: 21 Seller: John Adams Buyer: PriceCo Amt: $640,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-5: Sort Transactions with Comparator


Chapter 6 - Page 21
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Id: 15 Seller: Betty Jones Buyer: Radio Hut Amt: $800,000.00


Id: 13 Seller: Jane Doe Buyer: Radio Hut Amt: $2,000,000.00
Id: 23 Seller: Samuel Adams Buyer: Radio Hut Amt: $1,040,000.00

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-5: Sort Transactions with Comparator


Chapter 6 - Page 22
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-6: Collect Results with Streams

Overview
In this practice, use the collect method to store the results from a stream in a new list.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-06Prac project in the practice06 directory for this lesson.
2. Edit the CollectTest class to perform the steps in this practice.
3. Filter the transaction list to only include transactions greater than $300,000 sorted in

Oracle University and CCYD S.R.L. use only


ascending order.
4. Store the results in a new list using the collect method. For example:
.collect(Collectors.toList())
5. Print out the transactions in the new list. The output should look similar to the following:
=== Transactions over $300k ===
Id: 12 Seller: Jane Doe Buyer: Acme Electronics Amt: $400,000.00
Id: 16 Seller: Betty Jones Buyer: Best Deals Amt: $500,000.00
Id: 21 Seller: John Adams Buyer: PriceCo Amt: $640,000.00
Id: 15 Seller: Betty Jones Buyer: Radio Hut Amt: $800,000.00
Id: 19 Seller: Betty Jones Buyer: Best Deals Amt: $800,000.00
Id: 23 Seller: Samuel Adams Buyer: Radio Hut Amt: $1,040,000.00
Id: 13 Seller: Jane Doe Buyer: Radio Hut Amt: $2,000,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-6: Collect Results with Streams


Chapter 6 - Page 23
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-7: Join Data with Streams

Overview
In this practice, use the joining method to combine data returned from a stream.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-07Prac project in the practice07 directory for this lesson.
2. Edit the JoinTest class to perform the steps in this practice.
3. Get a list of unique buyer names in a sorted order. Follow these steps to accomplish the

Oracle University and CCYD S.R.L. use only


task:
a. Use map to get all the buyer names.
b. Use distinct to remove duplicates.
c. Use sorted to sort the names.
d. Use joining to join the names together in the output you see in the following.
4. When complete, your output should look similar to the following:
=== Sorted Buyer's List ===
Buyer list: Acme Electronics, Best Deals, Mom and Pops, PriceCo,
Radio Hut

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-7: Join Data with Streams


Chapter 6 - Page 24
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-8: Group Data with Streams

Overview
In this practice, create a Map of transaction data using the groupingBy method from the
Collectors class.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-08Prac project in the practice08 directory for this lesson.
2. Edit the GroupTest class to perform the steps in this practice.

Oracle University and CCYD S.R.L. use only


3. Populate the Map by using the stream collect method to return the list elements grouped
by buyer name.
a. Use Collectors.groupingBy() to group the results.
b. Use SalesTxn::getBuyerName to determine what to group by.
4. Print out the result.
5. Use the printSummary method of the SalesTxn class to print individual transactions.
6. Your output should look similar to the following:
=== Transactions Grouped by Buyer ===

Buyer: PriceCo
ID: 17 - Seller: Dave Smith - Buyer: PriceCo - Product: Widget Pro - ST: CO - Amt:
240000.0 - Date: 2013-03-20
ID: 18 - Seller: Dave Smith - Buyer: PriceCo - Product: Widget - ST: CO - Amt:
300000.0 - Date: 2013-03-30
ID: 20 - Seller: John Adams - Buyer: PriceCo - Product: Widget - ST: MA - Amt:
280000.0 - Date: 2013-07-14
ID: 21 - Seller: John Adams - Buyer: PriceCo - Product: Widget Pro - ST: MA - Amt:
640000.0 - Date: 2013-10-06

Buyer: Acme Electronics


ID: 11 - Seller: Jane Doe - Buyer: Acme Electronics - Product: Widgets - ST: CA -
Amt: 60000.0 - Date: 2013-01-25
ID: 12 - Seller: Jane Doe - Buyer: Acme Electronics - Product: Widget Pro - ST: CA
- Amt: 400000.0 - Date: 2013-04-05

Buyer: Radio Hut


ID: 13 - Seller: Jane Doe - Buyer: Radio Hut - Product: Widget Pro - ST: CA - Amt:
2000000.0 - Date: 2013-10-03
ID: 15 - Seller: Betty Jones - Buyer: Radio Hut - Product: Widget Pro - ST: CO -
Amt: 800000.0 - Date: 2013-02-04
ID: 23 - Seller: Samuel Adams - Buyer: Radio Hut - Product: Widget Pro - ST: MA -
Amt: 1040000.0 - Date: 2013-12-08

Buyer: Mom and Pops


ID: 22 - Seller: Samuel Adams - Buyer: Mom and Pops - Product: Widget - ST: MA -
Amt: 60000.0 - Date: 2013-10-02

Buyer: Best Deals


ID: 16 - Seller: Betty Jones - Buyer: Best Deals - Product: Widget - ST: CO - Amt:
500000.0 - Date: 2013-03-21
ID: 19 - Seller: Betty Jones - Buyer: Best Deals - Product: Widget Pro - ST: CO -
Amt: 800000.0 - Date: 2013-07-12

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-8: Group Data with Streams


Chapter 6 - Page 25
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Buyer: Great Deals


ID: 14 - Seller: John Smith - Buyer: Great Deals - Product: Widget - ST: CA - Amt:
100000.0 - Date: 2013-10-10

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-8: Group Data with Streams


Chapter 6 - Page 26
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-9: Partition Data with Streams

Overview
In this practice, partition the transactions into a Map based on total transaction amount.

Assumptions
You have completed the lecture portion of the course.

Tasks
1. Open the SalesTxn06-09Prac project in the practice09 directory for this lesson.
2. Edit the PartitionTest class to perform the steps in this practice.
3. Convert the transaction list into a Map by partitioning the data in a group greater than or

Oracle University and CCYD S.R.L. use only


equal to $400,000 and another group less than that amount using the partitioningBy
method.
4. Print the resulting Map. Your output should look similar to the following:
=== Transactions Partition ===

T/F: false
ID: 11 - Seller: Jane Doe - Buyer: Acme Electronics - Product: Widgets - ST: CA -
Amt: 60000.0 - Date: 2013-01-25
ID: 14 - Seller: John Smith - Buyer: Great Deals - Product: Widget - ST: CA - Amt:
100000.0 - Date: 2013-10-10
ID: 17 - Seller: Dave Smith - Buyer: PriceCo - Product: Widget Pro - ST: CO - Amt:
240000.0 - Date: 2013-03-20
ID: 18 - Seller: Dave Smith - Buyer: PriceCo - Product: Widget - ST: CO - Amt:
300000.0 - Date: 2013-03-30
ID: 20 - Seller: John Adams - Buyer: PriceCo - Product: Widget - ST: MA - Amt:
280000.0 - Date: 2013-07-14
ID: 22 - Seller: Samuel Adams - Buyer: Mom and Pops - Product: Widget - ST: MA -
Amt: 60000.0 - Date: 2013-10-02

T/F: true
ID: 12 - Seller: Jane Doe - Buyer: Acme Electronics - Product: Widget Pro - ST: CA
- Amt: 400000.0 - Date: 2013-04-05
ID: 13 - Seller: Jane Doe - Buyer: Radio Hut - Product: Widget Pro - ST: CA - Amt:
2000000.0 - Date: 2013-10-03
ID: 15 - Seller: Betty Jones - Buyer: Radio Hut - Product: Widget Pro - ST: CO -
Amt: 800000.0 - Date: 2013-02-04
ID: 16 - Seller: Betty Jones - Buyer: Best Deals - Product: Widget - ST: CO - Amt:
500000.0 - Date: 2013-03-21
ID: 19 - Seller: Betty Jones - Buyer: Best Deals - Product: Widget Pro - ST: CO -
Amt: 800000.0 - Date: 2013-07-12
ID: 21 - Seller: John Adams - Buyer: PriceCo - Product: Widget Pro - ST: MA - Amt:
640000.0 - Date: 2013-10-06
ID: 23 - Seller: Samuel Adams - Buyer: Radio Hut - Product: Widget Pro - ST: MA -
Amt: 1040000.0 - Date: 2013-12-08

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-9: Partition Data with Streams


Chapter 6 - Page 27
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-10: Calculate Sales Totals from Multiple Companies


(Optional)

Overview
In this practice, calculate the sales totals from multiple buyers from the collection of sales
transactions using the summingDoubles method.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn06-10Prac project in the practice10 directory for this lesson or

Oracle University and CCYD S.R.L. use only


continue with the project from the last practice.
2. Edit the CalcTest class to perform the steps in this practice.
3. Filter transactions for Radio Hut, PriceCo, and Best Deals. (Hint: Use a compound
conditional or consider using a Set.)
4. Collect and sum the result using summingDoubles. Use groupingBy to group the results
by buyer name.
5. Print the results.
6. The output from your test class should be similar to the following:
=== Sales Report
PriceCo Sales: $1,460,000.00
Radio Hut Sales: $3,840,000.00
Best Deals Sales: $1,300,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 6-10: Calculate Sales Totals from Multiple Companies (Optional)


Chapter 6 - Page 28
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 7: Overview


Chapter 7 - Page 1
Chapter 7

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.


Parallel Streams
Practices for Lesson 7:

Oracle University and CCYD S.R.L. use only


THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 7: Overview

Practice Overview
In these practices, explore the parallel stream options available in Java.

Old Style Loop


The following example iterates through an Employee list. Each member who is from Colorado
and is an executive has their information printed out. In addition, the sum mutator is used to
calculate the total amount of executive pay for the selected group.
A01OldStyleLoop.java
9 public class A01OldStyleLoop {
10
11 public static void main(String[] args) {

Oracle University and CCYD S.R.L. use only


12
13 List<Employee> eList = Employee.createShortList();
14
15 double sum = 0;
16
17 for(Employee e:eList){
18 if(e.getState().equals("CO") &&
19 e.getRole().equals(Role.EXECUTIVE)){
20 e.printSummary();
21 sum += e.getSalary();
22 }
23 }
24
25 System.out.printf("Total CO Executive Pay: $%,9.2f %n", sum);
26 }
27
28 }
There are a couple of key points that can be made about the above code.
• All elements in the collections must be iterated through every time.
• The code is more about "how" information is obtained and less about "what" the code
is trying to accomplish.
• A mutator must be added to the loop to calculate the total.
• There is no easy way to parallelize this code.
The output from the program is as follows.
Output
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Total CO Executive Pay: $370,000.00

Lambda Style Loop


The following example shows the new approach to obtaining the same data using lambda
expressions. A stream is created, filtered, and printed. A map method is used to extract the
salary data, which is then summed and returned.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A02NewStyleLoop.java
9 public class A02NewStyleLoop {
10
11 public static void main(String[] args) {
12
13 List<Employee> eList = Employee.createShortList();
14
15 double result = eList.stream()
16 .filter(e -> e.getState().equals("CO"))
17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .peek(e -> e.printSummary())
19 .mapToDouble(e -> e.getSalary())
20 .sum();
21
22 System.out.printf("Total CO Executive Pay: $%,9.2f %n",

Oracle University and CCYD S.R.L. use only


result);
23 }
24
25 }
There are also some key points worth pointing out for this piece of code as well.
• The code reads much more like a problem statement.
• No mutator is needed to get the final result.
• Using this approach provides more opportunity for lazy optimizations.
• This code can easily be parallelized.
The output from the example is as follows.
Output
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Total CO Executive Pay: $370,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Streams with Code


So far all the examples have used lambda expressions and stream pipelines to perform the
tasks. In this example, the Stream class is used with regular Java statements to perform the
same steps as those found in a pipeline.
A03CodeStream.java
11 public class A03CodeStream {
12
13 public static void main(String[] args) {
14
15 List<Employee> eList = Employee.createShortList();
16
17 Stream<Employee> s1 = eList.stream();
18

Oracle University and CCYD S.R.L. use only


19 Stream<Employee> s2 = s1.filter(
20 e -> e.getState().equals("CO"));
21
22 Stream<Employee> s3 = s2.filter(
23 e -> e.getRole().equals(Role.EXECUTIVE));
24 Stream<Employee> s4 = s3.peek(e -> e.printSummary());
25 DoubleStream s5 = s4.mapToDouble(e -> e.getSalary());
26 double result = s5.sum();
27
28 System.out.printf("Total CO Executive Pay: $%,9.2f %n",
result);
29 }
30
31 }
Even though the approach is possible, a stream pipeline seems like a much better solution.
The output from the program is as follows.
Output
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Total CO Executive Pay: $370,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Making a Stream Parallel


Making a stream run in parallel is pretty easy. Just call the parallelStream or parallel
method in the stream. With that call, when the stream executes it uses all the processing cores
available to the current JVM to perform the task.
A04Parallel.java
9 public class A04Parallel {
10
11 public static void main(String[] args) {
12
13 List<Employee> eList = Employee.createShortList();
14
15 double result = eList.parallelStream()
16 .filter(e -> e.getState().equals("CO"))

Oracle University and CCYD S.R.L. use only


17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .peek(e -> e.printSummary())
19 .mapToDouble(e -> e.getSalary())
20 .sum();
21
22 System.out.printf("Total CO Executive Pay: $%,9.2f %n",
result);
23
24 System.out.println("\n");
25
26 // Call parallel from pipeline
27 result = eList.stream()
28 .filter(e -> e.getState().equals("CO"))
29 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
30 .peek(e -> e.printSummary())
31 .mapToDouble(e -> e.getSalary())
32 .parallel()
33 .sum();
34
35 System.out.printf("Total CO Executive Pay: $%,9.2f %n",
result);
36
37 System.out.println("\n");
38
39 // Call sequential from pipeline
40 result = eList.stream()
41 .filter(e -> e.getState().equals("CO"))
42 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
43 .peek(e -> e.printSummary())
44 .mapToDouble(e -> e.getSalary())
45 .sequential()
46 .sum();
47
48 System.out.printf("Total CO Executive Pay: $%,9.2f %n",
result);
49 }
50 }
Remember, the last call wins. So if you call the sequential method after the parallel method in
your pipeline, the pipeline will execute serially.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

The following output is produced for this sample program.


Output
Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Total CO Executive Pay: $370,000.00

Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00
Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Total CO Executive Pay: $370,000.00

Name: Joe Bailey Role: EXECUTIVE Dept: Eng St: CO Salary: $120,000.00

Oracle University and CCYD S.R.L. use only


Name: Phil Smith Role: EXECUTIVE Dept: HR St: CO Salary: $110,000.00
Name: Betty Jones Role: EXECUTIVE Dept: Sales St: CO Salary: $140,000.00
Total CO Executive Pay: $370,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Stateful Versus Stateless Operations


You should avoid using stateful operations on collections when using stream pipelines. The
collect method and Collectors class have been designed to work with both serial and
parallel pipelines.
A05AvoidStateful.java
11 public class A05AvoidStateful {
12
13 public static void main(String[] args) {
14
15 List<Employee> eList = Employee.createShortList();
16 List<Employee> newList01 = new ArrayList<>();
17 List<Employee> newList02 = new ArrayList<>();
18

Oracle University and CCYD S.R.L. use only


19 eList.stream() // Not Parallel. Bad.
20 .filter(e -> e.getDept().equals("Eng"))
21 .forEach(e -> newList01.add(e));
22
23 newList02 = eList.stream() // Good Parallel
24 .filter(e -> e.getDept().equals("Eng"))
25 .collect(Collectors.toList());
26
27 }
28 }

Lines 19 to 21 show you how NOT to extract data from a pipeline. Your operations may not be
thread safe. Lines 23 to 25 demonstrate the correct method for saving data from a pipeline
using the collect method and Collectors class.

Deterministic and Non-Deterministic Operations


Most stream pipelines are deterministic. That means that whether the pipeline is processed
serially or in parallel the result will be the same.
A06Determine.java
10 public class A06Determine {
11
12 public static void main(String[] args) {
13
14 List<Employee> eList = Employee.createShortList();
15
16 double r1 = eList.stream()
17 .filter(e -> e.getState().equals("CO"))
18 .mapToDouble(Employee::getSalary)
19 .sequential().sum();
20
21 double r2 = eList.stream()
22 .filter(e -> e.getState().equals("CO"))
23 .mapToDouble(Employee::getSalary)
24 .parallel().sum();
25
26 System.out.println("The same: " + (r1 == r2));
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

27 }
28 }
The example shows that the result for a sum is the same that is processed using either
highlighted method.
The output from the sample is as follows:
Output
The same: true

However, some operations are not deterministic. The findAny() method is a short-circuit
terminal operation that may produce different results when processed in parallel.
A07DertermineNot.java

Oracle University and CCYD S.R.L. use only


10 public class A07DetermineNot {
11
12 public static void main(String[] args) {
13
14 List<Employee> eList = Employee.createShortList();
15
16 Optional<Employee> e1 = eList.stream()
17 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
18 .sequential().findAny();
19
20 Optional<Employee> e2 = eList.stream()
21 .filter(e -> e.getRole().equals(Role.EXECUTIVE))
22 .parallel().findAny();
23
24 System.out.println("The same: " +
25 e1.get().getEmail().equals(e2.get().getEmail()));
26
27 }
28 }
The data set used in the example is fairly small therefore the two different approaches will often
produce the same result. However, with a larger data set, it becomes more likely that the results
produced will not be the same.

Reduction
The reduce method performs reduction operations for the stream libraries. The following
example sums numbers 1 to 5.
A08Reduction.java
9 public class A08Reduction {
10
11 public static void main(String[] args) {
12
13 int r1 = IntStream.rangeClosed(1, 5)
14 .reduce(0, (a, b) -> a + b);
15
16 System.out.println("Result: " + r1);
17
18 int r2 = IntStream.rangeClosed(1, 5)

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

19 .reduce(0, (sum, element) -> sum + element);


20
21 System.out.println("Result: " + r2);
22
23 }
24
25 }
Two examples are shown. The second example started on line 18 uses more description
variables to show how the two variables are used. The left value is used as an accumulator. The
value on the right is added to the value on the left. Reductions must be associative operations to
get a correct result.

The output from both expressions should be the following:

Oracle University and CCYD S.R.L. use only


Output
Result: 15
Result: 15

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Overview


Chapter 7 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-1: Calculate Total Sales without a Pipeline

Overview
In this practice, calculate the sales total for Radio Hut using the Stream class and normal Java
statements.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn07-01Prac project in the practice01 directory for this lesson.
2. Edit the CalcTest class to perform the steps in this practice.

Oracle University and CCYD S.R.L. use only


3. Calculate the total sales for Radio Hut using the Stream class and Java statements.
Create a stream from tList and assign it to: Stream<SalesTxn> s1
Create a second stream and assign the results of the filter method for Radio Hut
transactions: Stream<SalesTxn> s2
Create a third stream and assign the results from a mapToDouble method that returns the
transaction total: DoubleStream s3
Sum the final stream and assign the result to: double t1.
4. Print the results.
Hint: Be mindful of the method return types. Use the API doc to ensure that you are using
the correct methods and classes to create and store results.
5. The output from your test class should be similar to the following:
=== Transactions Totals ===
Radio Hut Total: $3,840,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 7-1: Calculate Total Sales without a Pipeline


Chapter 7 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-2: Calculate Sales Totals using Parallel Streams

Overview
In this practice, calculate the sales totals from the collection of sales transactions.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn07-02Prac project in the practice02 directory for this lesson.
2. Edit the CalcTest class to perform the steps in this practice.
3. Calculate the total sales for Radio Hut, PriceCo, and Best Deals.

Oracle University and CCYD S.R.L. use only


a. Calculate the Radio Hut total using the parallelStream method. The pipeline should
contain the following methods: parallelStream, filter, mapToDouble, and sum.
b. Calculate the PriceCo total using the parallel method. The pipeline should contain
the following methods: filter, mapToDouble, parallel, and sum.
c. Calculate the Best Deals total using the sequential method. The pipeline should
contain the following methods: filter, mapToDouble, sequential, and sum.
4. Print the results.
5. The output from your test class should be similar to the following:
=== Transactions Totals ===
Radio Hut Total: $3,840,000.00
PriceCo Total: $1,460,000.00
Best Deals Total: $1,300,000.00

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 7-2: Calculate Sales Totals using Parallel Streams


Chapter 7 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-3: Calculate Sales Totals Using Parallel Streams and


Reduce

Overview
In this practice, calculate the sales totals from the collection of sales transactions using the
reduce method.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn07-03Prac project in the practice03 directory for this lesson or

Oracle University and CCYD S.R.L. use only


continue with the project from the last practice.
2. Edit the CalcTest class to perform the steps in this practice.
3. Calculate the total sales PriceCo using the reduce method instead of sum.
a. Your pipeline should consist of: filter, mapToDouble, parallel, and reduce
b. The reduce function can be defined as: reduce(0, (sum, e) -> sum + e)
4. In addition, calculate the total number of transactions for PriceCo using map and reduce.
a. Your pipeline should consist of: filter, mapToDouble, parallel, and reduce.
b. To count the transactions, use: map(t -> 1)
c. The reduce function can be defined as: reduce(0, (sum, e) -> sum + e)
5. Print the results.
6. The output from your test class should be similar to the following:
=== Transactions Totals ===

PriceCo Total: $1,460,000.00


PriceCo Transactions: 4

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 7-3: Calculate Sales Totals Using Parallel Streams and Reduce
Chapter 7 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 8: Overview


Chapter 8 - Page 1
Chapter 8

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.


Lambda Cookbook
Practices for Lesson 8:

Oracle University and CCYD S.R.L. use only


THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 8: Overview

Practice Overview
In these practices, explore various new features in Java 8 that relate to lambda expressions or
streams.

ArrayList removeIf
The new ArrayList removeIf method allows you to remove elements from an ArrayList
using a Predicate.
A01RemoveIf.java
9 public class A01RemoveIf {
10 public static void main(String[] args) {

Oracle University and CCYD S.R.L. use only


11 ArrayList<Employee> eList =
12 (ArrayList) Employee.createShortList();
13
14 System.out.println("=== Starting List ===");
15 eList.forEach(Employee::printSummary);
16
17 eList.removeIf(e -> e.getState().equals("KS"));
18
19 System.out.println("=== Ending List ===");
20 eList.forEach(Employee::printSummary);
21
22 }
23 }
In this example, any elements in the list that have a state value of "KS" are removed from the
list.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

ArrayList ReplaceAll
The ArrayList replaceAll method can be used to replace all the elements in a list.
A02ReplaceAll.java
10 public class A02ReplaceAll {
11 public static void main(String[] args) {
12 ArrayList<Employee> eList =
13 (ArrayList) Employee.createShortList();
14
15 System.out.println("=== Starting List ===");
16 eList.forEach(Employee::printSummary);
17
18 eList.replaceAll(e ->
19 new Employee.Builder()

Oracle University and CCYD S.R.L. use only


20 .givenName("Bob")
21 .surName("Baker")
22 .age(23)
23 .gender(Gender.MALE)
24 .role(Role.STAFF)
25 .dept("Eng")
26 .startDate(LocalDate.of(2013, 1, 10))
27 .salary(40000)
28 .email("bob.baker@example.com")
29 .phoneNumber("201-121-4678")
30 .address("44 4th St")
31 .city("Smallville")
32 .state("KS")
33 .code("12333")
34 .build()
35 );
36
37 System.out.println("\n=== Ending List ===");
38 eList.forEach(Employee::printSummary);
39
40 }
41 }
The example replaces all the elements in the list with a new Employee instance populated with
the data for Bob Baker. Each element is replaced with the result from the Lambda expression.

Map ComputeIfAbsent
The Map interface has some new features as well. The computeIfAbsent method allows you
to create an entry in the map if none exists. The method call includes the key to search for along
with a lambda expression, which defines what value should be stored.
A03ComputeIfAbsent.java
11 public class A03ComputeIfAbsent {
12
13 private static final String placeHolder = "TBD";
14
15 public static void main(String[] args) {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

16
17 Map<String, String> stMap = new HashMap<>();
18
19 stMap.put("WY", "Cheyenne");
20 stMap.put("SD", "Pierre");
21 stMap.put("CO", "Denver");
22
23 stMap.computeIfAbsent("AL", v -> placeHolder);
24
25 System.out.println("=== Print Map ===");
26 stMap.forEach(
27 (k, v) -> System.out.println("Key: " + k + " "
28 + "Value: " + v));
29 }

Oracle University and CCYD S.R.L. use only


30 }
The example searches the map for a key value of "AL." When the key is not found, the map
entry is inserted by the method.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Map ComputeIfPresent
The computeIfPresent method allows you to update a value if the key is present. Notice that
the parameters passed are a little different. A BiFunction is used to set the value of that map
entry.
A04ComputeIfPresent.java
11 public class A04ComputeIfPresent {
12
13 public static void main(String[] args) {
14
15 Map<String, String> stMap = new HashMap<>();
16
17 stMap.put("WY", "Cheyenne");

Oracle University and CCYD S.R.L. use only


18 stMap.put("SD", "Pierre");
19 stMap.put("CO", "Denver");
20
21 stMap.computeIfPresent("WY",
22 (k,v) -> v + " (Verified " + k + ")");
23
24 System.out.println("=== Print Map ===");
25 stMap.forEach(
26 (k, v) -> System.out.println("Key: " + k + " "
27 + "Value: " + v));
28
29 }
30
31 }
In this example, a match is found for "WY." Note that the lambda expression passed as the
second parameter.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Streaming Map Keys and Values


This example demonstrates how to create a stream for a map's keys or values. The first block of
code starting on line 24 takes a map's keys and converts them into an array. The second
example starting on line 29 shows how values can be streamed.
A05MapStream.java
11 public class A05MapStream {
12
13 public static void main(String[] args) {
14
15 Map<String, String> stMap = new HashMap<>();
16
17 stMap.put("WY", "Cheyenne");
18 stMap.put("SD", "Pierre");

Oracle University and CCYD S.R.L. use only


19 stMap.put("CO", "Denver");
20 stMap.put("CA", "Sacramento");
21 stMap.put("DE", "Dover");
22
23 // Stream Key's
24 stMap.keySet().stream()
25 .filter(s -> s.startsWith("C"))
26 .forEach(s -> System.out.println("State: " + s));
27
28 // Stream Values
29 stMap.values().stream()
30 .filter(s -> s.startsWith("D"))
31 .forEach(s -> System.out.println("City: " + s));
32 }
33
34 }
Both examples take the resulting stream and apply a filter to the result.

Map Merge
The merge method is used to update the value of a map entry. The method takes a key, a
message value, and a BiFunction as parameters. The BiFunction has the message and
current map entry passed as parameters. The return value of the function becomes the new
map value.
A06MapMerge.java
16 public class A06MapMerge {
17 public static void main(String[] args) {
18 Map<String, String> stMap = new HashMap<>();
19 String message = " (Verified C State)";
20
21 stMap.put("WY", "Cheyenne");
22 stMap.put("SD", "Pierre");
23 stMap.put("CO", "Denver");
24 stMap.put("CA", "Sacramento");
25 stMap.put("DE", "Dover");
26
27 // Stream Key's

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

28 List<String> cList = stMap.keySet().stream()


29 .filter(s -> s.startsWith("C"))
30 .collect(Collectors.toList());
31
32 cList.stream().forEach((e) -> {
33 stMap.merge(e, message, (s,m) -> s.concat(m));
34 });
35
36 stMap.forEach((k,v) ->
37 System.out.println("Key: " + k + " Value: " + v));
38 }
39 }
In this example, keys that start with "C" are extracted from the map and then used to update the
values of the matching entries.

Oracle University and CCYD S.R.L. use only


Using Stream.of
The of method of the Stream class allows you to simply and easily create a stream. The
syntax is pretty straightforward.
A07StreamOf.java
9 public class A07StreamOf {
10 public static void main(String[] args) {
11
12 Stream.of("Monday", "Tuesday","Wedensday", "Thursday")
13 .filter(s -> s.startsWith("T"))
14 .forEach(s -> System.out.println("Matching Days: " + s));
15 }
16 }
The example creates a stream out of string values and filters them.

Tempest.txt File
The following file is used for all the file examples that follow.
tempest.txt
PROSPERO. You do look, my son, in a mov'd sort,
As if you were dismay'd; be cheerful, sir.
Our revels now are ended. These our actors,
As I foretold you, were all spirits, and
Are melted into air, into thin air;
And, like the baseless fabric of this vision,
The cloud-capp'd towers, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,
Leave not a rack behind. We are such stuff
As dreams are made on; and our little life
Is rounded with a sleep. Sir, I am vex'd;
Bear with my weakness; my old brain is troubled;
Be not disturb'd with my infirmity.
If you be pleas'd, retire into my cell

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

And there repose; a turn or two I'll walk


To still my beating mind.
FERDINAND, MIRANDA. We wish your peace. Exeunt
PROSPERO. Come, with a thought. I thank thee, Ariel; come.

Reading a File with Buffered Reader


The lines method is new to Java 8. It allows you to take something, say a file, and turn it into a
stream. This example converts a BufferedReader into a stream.
A08BufferedReader.java
11 public class A08BufferedRead {
12 public static void main(String[] args) {
13 try(BufferedReader bReader =

Oracle University and CCYD S.R.L. use only


14 new BufferedReader(new FileReader("tempest.txt"))){
15
16 bReader.lines()
17 .forEach(line ->
18 System.out.println("Line: " + line));
19
20 } catch (IOException e){
21 System.out.println("Message: " + e.getMessage());
22 }
23 }
24 }
The example reads a text file and prints the contents to standard out.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Reading a File using NIO


The lines method can also be use with New IO (NIO) classes. The example also reads a file and
prints its contents to standard out. However, NIO classes are used here.
A09aReadNio.java
1 package com.example.lambda;
2
3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Paths;
6 import java.util.stream.Stream;
7
8 /**
9 *

Oracle University and CCYD S.R.L. use only


10 * @author oracle
11 */
12 public class A09aReadNio {
13
14 public static void main(String[] args) {
15
16 try(Stream<String> lines =
17 Files.lines(Paths.get("tempest.txt"))){
18
19 lines.forEach(line ->
20 System.out.println("Line: " + line));
21
22 } catch (IOException e){
23 System.out.println("Error: " + e.getMessage());
24 }
25 }
26 }
Notice in the try-with-resources Paths.get returns a file handle. Then, Files.lines returns
a stream of String elements representing the lines in the file. At this point, the stream can be
printed out or filtered further.

Read a File into an ArrayList


This example shows how to read a text file into an ArrayList using the readAllLines
method. The advantage to this approach is that multiple streams can be generated from the file
contents, which are now an ArrayList.
A09bReadAllNio.java
13 public class A09bReadAllNio {
14
15 public static void main(String[] args) {
16
17 Path file = Paths.get("tempest.txt");
18 List<String> fileArr;
19
20 try{
21
22 fileArr = Files.readAllLines(file);

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

23
24 fileArr.stream()
25 .filter(line -> line.contains("PROSPERO"))
26 .forEach(line -> System.out.println(line));
27
28 } catch (IOException e){
29 System.out.println("Message: " + e.getMessage());
30 }
31 }
32 }
After reading the file into an ArrayList, the array is filtered for the word "PROSPERO." The
lines that match are printed out.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Get a list of Directory Contents


The Files.list method allows you to generate a stream of the files in the selected path.
A10FileList.java
1 package com.example.lambda;
2
3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.nio.file.Paths;
7 import java.util.stream.Stream;
8
9 /**
10 *

Oracle University and CCYD S.R.L. use only


11 * @author oracle
12 */
13 public class A10FileList {
14
15 public static void main(String[] args) {
16
17 try(Stream<Path> files = Files.list(Paths.get("."))){
18
19 files
20 .forEach(line -> System.out.println(line));
21
22 } catch (IOException e){
23 System.out.println("Message: " + e.getMessage());
24 }
25 }
26 }
The example takes the file list and prints it out.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Walk the Directory Tree


The Files.walk method walks the current directory and all the subdirectories using the
selected path. Results are turned into a stream and can be filtered.
A11FileWalk.java
1 package com.example.lambda;
2
3 import java.nio.file.Files;
4 import java.nio.file.Path;
5 import java.nio.file.Paths;
6 import java.util.stream.Stream;
7
8 /**
9 *

Oracle University and CCYD S.R.L. use only


10 * @author oracle
11 */
12 public class A11FileWalk {
13
14 public static void main(String[] args) {
15
16 try(Stream<Path> files = Files.walk(Paths.get("."))){
17
18 files
19 .forEach(line -> System.out.println(line));
20
21 } catch (Exception e){
22 System.out.println("Message: " + e.getMessage());
23 }
24 }
25 }
This example prints all the files in the directory tree.

Search a Directory Tree

The Files.find method allows you to search a directory tree based on file attributes.
A12FileFind.java
1 package com.example.lambda;
2
3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.nio.file.Paths;
7 import java.util.stream.Stream;
8
9 /**
10 *
11 * @author oracle
12 */
13 public class A12FileFind {
14
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

15 public static void main(String[] args) {


16
17 try(Stream<Path> files =
18 Files.find(
19 Paths.get("."), 9, (p, a) -> a.isDirectory())){
20
21 files
22 .forEach(f -> System.out.println("Dirname: " + f));
23
24 } catch (IOException e){
25 System.out.println("Message: " + e.getMessage());
26 }
27 }
28 }

Oracle University and CCYD S.R.L. use only


The example filters the results for directories and prints the results.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 13
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Using a FlatMap
The Stream.flatMap method can be used to generate a new flatter stream from an input
stream. In this example, a text file is read into a stream. The stream of lines is then "flattened"
into a stream of words.
A13FlatMap.java
1 package com.example.lambda;
2
3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Paths;
6 import java.util.stream.Stream;
7
8 /**

Oracle University and CCYD S.R.L. use only


9 *
10 * @author oracle
11 */
12 public class A13FlatMap {
13
14 public static void main(String[] args) {
15
16 try(Stream<String> lines =
17 Files.lines(Paths.get("tempest.txt"))){
18
19 long matches = lines
20 .flatMap(line -> Stream.of(line.split(" ")))
21 .filter(word -> word.contains("my"))
22 .peek(s -> System.out.println("Match: " + s))
23 .count();
24
25 System.out.println("# of Matches: " + matches);
26 } catch (IOException e){
27 System.out.println("Message: " + e.getMessage());
28 }
29 }
30 }
In the example, the text file is flattened so that words can be displayed and counted.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Overview


Chapter 8 - Page 14
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-1: Working with ArrayLists

Overview
In this practice, explore the new methods added to the ArrayList class.

Assumptions
You have completed the lecture portion of this lesson.

Tasks
1. Open the SalesTxn08-01Prac project in the practice01 directory for this lesson.
2. Edit the P01RemoveIf class to perform the following steps.
3. Print out the starting values in the list. The output should be similar to the following:

Oracle University and CCYD S.R.L. use only


===Starting List===
ID: 11 - Buyer: Acme Electronics - Prod: Widgets - ST: CA - Amt: 60000.0
ID: 12 - Buyer: Acme Electronics - Prod: Widget Pro - ST: CA - Amt:
400000.0
ID: 13 - Buyer: Radio Hut - Prod: Widget Pro - ST: CA - Amt: 2000000.0
ID: 14 - Buyer: Great Deals - Prod: Widget - ST: CA - Amt: 100000.0
ID: 15 - Buyer: Radio Hut - Prod: Widget Pro - ST: CO - Amt: 800000.0
ID: 16 - Buyer: Best Deals - Prod: Widget - ST: CO - Amt: 500000.0
ID: 17 - Buyer: PriceCo - Prod: Widget Pro - ST: CO - Amt: 240000.0
ID: 18 - Buyer: PriceCo - Prod: Widget - ST: CO - Amt: 300000.0
ID: 19 - Buyer: Best Deals - Prod: Widget Pro - ST: CO - Amt: 800000.0
ID: 20 - Buyer: PriceCo - Prod: Widget - ST: MA - Amt: 280000.0
ID: 21 - Buyer: PriceCo - Prod: Widget Pro - ST: MA - Amt: 640000.0
ID: 22 - Buyer: Mom and Pops - Prod: Widget - ST: MA - Amt: 60000.0
ID: 23 - Buyer: Radio Hut - Prod: Widget Pro - ST: MA - Amt: 1040000.0
4. Remove the Radio Hut transactions from the list using the removeIf method.
5. Print out the list again. The output should be similar to the following:
===Ending List===
ID: 11 - Buyer: Acme Electronics - Prod: Widgets - ST: CA - Amt: 60000.0
ID: 12 - Buyer: Acme Electronics - Prod: Widget Pro - ST: CA - Amt:
400000.0
ID: 14 - Buyer: Great Deals - Prod: Widget - ST: CA - Amt: 100000.0
ID: 16 - Buyer: Best Deals - Prod: Widget - ST: CO - Amt: 500000.0
ID: 17 - Buyer: PriceCo - Prod: Widget Pro - ST: CO - Amt: 240000.0
ID: 18 - Buyer: PriceCo - Prod: Widget - ST: CO - Amt: 300000.0
ID: 19 - Buyer: Best Deals - Prod: Widget Pro - ST: CO - Amt: 800000.0
ID: 20 - Buyer: PriceCo - Prod: Widget - ST: MA - Amt: 280000.0
ID: 21 - Buyer: PriceCo - Prod: Widget Pro - ST: MA - Amt: 640000.0
ID: 22 - Buyer: Mom and Pops - Prod: Widget - ST: MA - Amt: 60000.0
6. Edit the P02ReplaceAll class to perform the following steps.
7. Print out the starting values in the list. The output should be similar to the following:
===Starting List===
ID: 11 - Buyer: Acme Electronics - Prod: Widgets - ST: CA - Amt: 60000.0
ID: 12 - Buyer: Acme Electronics - Prod: Widget Pro - ST: CA - Amt:
400000.0
ID: 13 - Buyer: Radio Hut - Prod: Widget Pro - ST: CA - Amt: 2000000.0
ID: 14 - Buyer: Great Deals - Prod: Widget - ST: CA - Amt: 100000.0
ID: 15 - Buyer: Radio Hut - Prod: Widget Pro - ST: CO - Amt: 800000.0
ID: 16 - Buyer: Best Deals - Prod: Widget - ST: CO - Amt: 500000.0
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-1: Working with ArrayLists


Chapter 8 - Page 15
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

ID: 17 - Buyer: PriceCo - Prod: Widget Pro - ST: CO - Amt: 240000.0


ID: 18 - Buyer: PriceCo - Prod: Widget - ST: CO - Amt: 300000.0
ID: 19 - Buyer: Best Deals - Prod: Widget Pro - ST: CO - Amt: 800000.0
ID: 20 - Buyer: PriceCo - Prod: Widget - ST: MA - Amt: 280000.0
ID: 21 - Buyer: PriceCo - Prod: Widget Pro - ST: MA - Amt: 640000.0
ID: 22 - Buyer: Mom and Pops - Prod: Widget - ST: MA - Amt: 60000.0
ID: 23 - Buyer: Radio Hut - Prod: Widget Pro - ST: MA - Amt: 1040000.0
8. Replace all the transactions with the data for transaction 11 in the SalesTxn class using
the replaceAll method.
9. Print out the list again. The output should be similar to the following:
===Ending List===
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0

Oracle University and CCYD S.R.L. use only


ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0
ID: 11 - Buyer: Acme Electronics - Prod: Widget - ST: CA - Amt: 60000.0

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-1: Working with ArrayLists


Chapter 8 - Page 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-2: Working with Maps

Overview
In this practice, calculate the sales total for Radio Hut using the Stream class and normal Java
statements.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the SalesTxn08-02Prac project in the practice02 directory for this lesson.
2. Edit the P01Compute class to perform the steps that follow.

Oracle University and CCYD S.R.L. use only


3. Given the provided Map, use the computeIfPresent method to append a verification
message to any map entry with a key of "IT."
4. Print out the Map. The output should look similar to the following.
=== Map Contents ===
Key: UK Value: London
Key: JP Value: Tokyo
Key: CZ Value: Prague
Key: IT Value: Rome (Verified in IT)
Key: US Value: Washington
Key: CA Value: Ottawa

5. Edit the P02Merge class to perform the steps that follow.


6. Given the provided Map, use the merge method to append the provided verification
message to any key values that start with "C."
7. Print out the Map. The output should look similar to the following:
=== Map Contents ===
Key: UK Value: London
Key: JP Value: Tokyo
Key: CZ Value: Prague (Verified C Country)
Key: IT Value: Rome
Key: US Value: Washington
Key: CA Value: Ottawa (Verified C Country)

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-2: Working with Maps


Chapter 8 - Page 17
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-3: Working with Files

Overview
In this practice, read text files using new features in Java 8 and the lines method.

Assumptions
You have completed the lecture portion of this lesson and the previous practice. A text excerpt
from the play Hamlet has been provided to you as a test file in the root directory of the project.
The contents of the files are as follows.
Enter Rosencrantz and Guildenstern.

Pol. Fare you well, my lord.


Ham. These tedious old fools!

Oracle University and CCYD S.R.L. use only


Pol. You go to seek the Lord Hamlet. There he is.
Ros. [to Polonius] God save you, sir!
Exit [Polonius].
Guil. My honour'd lord!
Ros. My most dear lord!
Ham. My excellent good friends! How dost thou, Guildenstern? Ah,
Rosencrantz! Good lads, how do ye both?
Ros. As the indifferent children of the earth.
Guil. Happy in that we are not over-happy.
On Fortune's cap we are not the very button.
Ham. Nor the soles of her shoe?
Ros. Neither, my lord.
Ham. Then you live about her waist, or in the middle of her
favours?
Guil. Faith, her privates we.
Ham. In the secret parts of Fortune? O! most true! she is a
strumpet. What news ?
Ros. None, my lord, but that the world's grown honest.
Ham. Then is doomsday near! But your news is not true. Let me
question more in particular. What have you, my good friends,
deserved at the hands of Fortune that she sends you to prison
hither?
Guil. Prison, my lord?
Ham. Denmark's a prison.
Ros. Then is the world one.
Ham. A goodly one; in which there are many confines, wards, and
dungeons, Denmark being one o' th' worst.
Ros. We think not so, my lord.
Ham. Why, then 'tis none to you; for there is nothing either good
or bad but thinking makes it so. To me it is a prison.
Ros. Why, then your ambition makes it one. 'Tis too narrow for
your
mind.
Ham. O God, I could be bounded in a nutshell and count myself a
king of infinite space, were it not that I have bad dreams.
Guil. Which dreams indeed are ambition; for the very substance of
the ambitious is merely the shadow of a dream.
Ham. A dream itself is but a shadow.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-3: Working with Files


Chapter 8 - Page 18
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Tasks
1. Open the LambdaFiles08-03Prac project in the practice03 directory for this lesson.
2. Edit the P01BufferedReader class to perform the steps that follow.
3. Using a BufferedReader and a stream, read in and print out the hamlet.txt file.
4. The output should look like the preceding original text provided.
5. Edit the P02NioRead class to perform the steps that follow.
6. Using the Path, File, and Files classes and a stream to read and print the contents of
the hamlet.txt file.
7. The output should look like the original text provided above.
8. Edit the P03NioReadAll class to perform the steps that follow.
9. Using the NIO features and streams, read the contents of the hamlet.txt file into an

Oracle University and CCYD S.R.L. use only


ArrayList.
10. Filter and print out the lines for Rosencrantz. For example: String.contains("Ros.").
The output should look similar to the following:
=== Rosencrantz ===
Ros. [to Polonius] God save you, sir!
Ros. My most dear lord!
Ros. As the indifferent children of the earth.
Ros. Neither, my lord.
Ros. None, my lord, but that the world's grown honest.
Ros. Then is the world one.
Ros. We think not so, my lord.
Ros. Why, then your ambition makes it one. 'Tis too narrow for
your

11. Filter and print out the lines for Guildenstern ("Guil."). The output should look similar to
the following:
=== Guildenstern ===
Guil. My honour'd lord!
Guil. Happy in that we are not over-happy.
Guil. Faith, her privates we.
Guil. Prison, my lord?
Guil. Which dreams indeed are ambition; for the very substance of

12. Edit the P04NioReadAll class to perform the steps that follow.
13. Using the NIO features and streams, read the contents of the hamlet.txt file into an
ArrayList.
14. Flatten the lines into words using the flatMap method. For example:
.flatMap(line -> Stream.of(line.split(" ")).
15. Filter and print out the word "lord". Print a count of the number of times the word occurs.
The output should look similar to the following:
=== Lord Count ===
lord.
lord!
lord!
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-3: Working with Files


Chapter 8 - Page 19
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

lord.
lord,
lord?
lord.
Word count: 7

16. Filter and print out the word "prison". Print a count of the number of times the word
occurs. The output should look similar to the following:
=== Prison Count ===
prison
prison.
prison.
Word count: 3

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-3: Working with Files


Chapter 8 - Page 20
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-4: Working with Directories

Overview
In this practice, list directories and files using new features found in Java 8.

Assumptions
You have completed the lecture portion of this lesson and the previous practice.

Tasks
1. Open the LambdaFiles08-04Prac project in the practice04 directory for this lesson.
2. Edit the P01DirList class to perform the steps that follow.
3. Read all the files in the current directory using the list method.

Oracle University and CCYD S.R.L. use only


4. Print the results. The output should look similar to the following:
=== Dir list ===
./build
./hamlet.txt
./nbproject
./src
./manifest.mf
./build.xml
5. Edit the P02DirWalk class to perform the steps that follow.
6. Use the Files.walk method to read the directory tree for the project.
7. Print the results. The output should look similar to the following:
=== Dir walk ===
.
./build
./build/classes
./build/classes/.netbeans_update_resources
./build/classes/com
./build/classes/com/example
./build/classes/com/example/lambda
./build/classes/com/example/lambda/P01DirList.class
./build/classes/com/example/lambda/P02DirWalk.class
./build/classes/com/example/lambda/Main.class
./build/classes/com/example/lambda/P03DirFind.class
./build/classes/.netbeans_automatic_build
./hamlet.txt
./nbproject
./nbproject/project.xml
./nbproject/genfiles.properties
./nbproject/build-impl.xml
./nbproject/private
./nbproject/private/private.xml
./nbproject/private/private.properties
./nbproject/project.properties
./src
./src/com
./src/com/example

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-4: Working with Directories


Chapter 8 - Page 21
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

./src/com/example/lambda
./src/com/example/lambda/P02DirWalk.java
./src/com/example/lambda/P03DirFind.java
./src/com/example/lambda/P01DirList.java
./src/com/example/lambda/Main.java
./manifest.mf
./build.xml
8. Next, walk the directory tree and filter the results so that only paths containing "build" are
displayed.
9. The output should look similar to the following:
=== Dir build ===
./build
./build/classes

Oracle University and CCYD S.R.L. use only


./build/classes/.netbeans_update_resources
./build/classes/com
./build/classes/com/example
./build/classes/com/example/lambda
./build/classes/com/example/lambda/P01DirList.class
./build/classes/com/example/lambda/P02DirWalk.class
./build/classes/com/example/lambda/Main.class
./build/classes/com/example/lambda/P03DirFind.class
./build/classes/.netbeans_automatic_build
./nbproject/build-impl.xml
./build.xml

10. Edit the P03DirFind class to perform the steps that follow.
11. Use the Files.find method to search the directory structure for entries that are
directories.
12. Print the results. The output should look similar to the following:
=== Find all dirs ===
.
./build
./build/classes
./build/classes/com
./build/classes/com/example
./build/classes/com/example/lambda
./nbproject
./nbproject/private
./src
./src/com
./src/com/example
./src/com/example/lambda

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 8-4: Working with Directories


Chapter 8 - Page 22
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 9:
Method Enhancements
Chapter 9

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Method Enhancements


Chapter 9 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 9: Method Enhancements

Practice Overview
In these practices, you explore the use of static and default methods in interfaces.

Static Methods in Interfaces


The following is an example of implementing a static method in an interface:
interface Octagon{
static int cornerCount(){
return 8;
}}

Oracle University and CCYD S.R.L. use only


The following is an example of calling an interface’s static method:
Octagon.cornerCount();

Default Method Rules


Rule 1: The superclass method takes priority over the interface default.
• The superclass method may be concrete or abstract.
• Consider only the interface default if no method exists in the superclass.

Rule 2: Subtype interfaces take priority over supertype interfaces.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Method Enhancements


Chapter 9 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Rule 3: If there is a conflict, treat the default method as abstract.
• The concrete class must provide its own implementation.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Method Enhancements


Chapter 9 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-1: Using Static Methods in Interfaces

Overview
This exercise is intended to give you practice in writing and using static methods in interfaces.
You will be asked to set up scenarios and reflect on the results. You have been given three
interfaces named Shape, Circle, and Triangle; two classes named Sphere and Cone,
as well as a test class named ShapesTest, which contains a main method.

Assumptions
You have completed the lecture and reviewed the overview for this practice.

Tasks
1. Open the ShapesTest project in the practice01 directory for this lesson.

Oracle University and CCYD S.R.L. use only


2. Open the Shape.java interface and observe the static printType() method.
Supply a similar static method to each of the following: Circle.java, Triangle.java,
Sphere.java, and Cone.java. You will need to tweak the body of each method so that
it references the proper class.
3. Open ShapesTest.java. In the main method, call each of the five static
printType() methods you have seen.
4. Run the project and examine the output. Your output should look similar to the following:
Shape
Circle
Triangle
Sphere
Cone
5. Apply the following inheritance structure to the code:
Shape

Circle Triangle

Sphere Cone

6. Run the project again and examine the output. Does the inheritance structure affect the
output? Does inheritance have any effect on static methods in interfaces?

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 9-1: Using Static Methods in Interfaces


Chapter 9 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-2: Using Static and Default Methods in Interfaces

Overview
This exercise is intended to give you practice writing and using static and default methods in
interfaces. You will be given a partially implemented program and asked to complete the code.
This includes writing static and default methods.
The program you will complete will calculate the surface area of each shape in a list. The list is
reordered according to how closely each shape’s surface area matches a target surface area.
Note: The triangle used in this practice is an isosceles right triangle.

Assumptions
You have completed the lecture, reviewed the overview for this practice, and completed the
previous practice.

Oracle University and CCYD S.R.L. use only


Tasks
1. While in the same project as Practice 9-1, open ShapesTest.java. Or, open the
ShapesTest project in the practice02 directory if you did not finish Practice 9-1.
2. Remove the printType() method calls.
3. Find the code in ShapesTest.java that is commented out. Uncomment this code.
Observe how this code creates a list of shapes (Spheres and Cylinders), invokes the
.stream() method, and compares values using lambda expressions. NetBeans will
complain because several methods have not been created.
4. Begin providing the necessary methods. Open Shape.java and supply the following:
• A default double calcArea() method. Because Shape is too ambiguous a term to
a calculable area, let this method return 0. Provide no arguments for this method.
• A static double compareArea()method that returns the absolute value of the
difference between the target area and the surface area of the shape. Provide a double
target surface area and a shape as arguments.
• An abstract double getLength() method. Provide no arguments for this method.
5. Open the Sphere.java and Cone.java classes. NetBeans will complain that these two
classes must implement all abstract methods. Supply the necessary implementations for
the abstract methods so that they return the classes’ length data member.
6. Run the project. Your output should report an area of 0 for each shape. Steps 4 and 5
reveal a key difference between abstract and default methods:
• It is mandatory that abstract methods be implemented in concrete classes.
• It is optional that default methods be implemented in concrete classes since they
already have an implementation.
7. Although it is not mandatory that classes provide a new definition for default methods, you
may still find in necessary so that your program works properly. Open Circle.java and
Triangle.java. In these two interfaces, provide overriding default calcArea()
methods so that they calculate the correct area for each shape. Instead of providing arguments
for these methods, use getLength() instead. Note that the triangle is isosceles. Hints:

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 9-2: Using Static and Default Methods in Interfaces


Chapter 9 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Circle Triangle
a
r
Area = πr 2 Area = a2 /2
a

8. Try to run the project. Observe the following complaint given by NetBeans and consider
which default method inheritance rule is applicable:
Cone inherits unrelated defaults for calcArea() from types
Lesson09.Circle and Lesson09.Triangle
9. Supply the remaining default methods throughout the project as necessary. Use
getLength() instead of supplying arguments for these methods. Hints:

Oracle University and CCYD S.R.L. use only


Hypotenuse = sqrt( 2a2 )
Triangle

Surface Area =
Cone π(hypotenuse of triangle) + (area of circle)

Surface Area = 4πr2


Sphere

• The following code: Circle.super.calcArea() can be placed inside the Cone


class to reference the inherited calcArea() default method from the Circle class.
10. Run the project. Your output should look similar to the following:
Type: Cone length: 2.0 diff: 8.548 area: 21.452
Type: Cone length: 3.0 diff: 11.603 area: 41.603
Type: Sphere length: 1.0 diff: 17.434 area: 12.566
Type: Sphere length: 2.0 diff: 20.265 area: 50.265
Type: Cone length: 1.0 diff: 22.416 area: 7.584
Type: Cone length: 4.0 diff: 38.037 area: 68.037
Type: Cone length: 5.0 diff: 70.754 area: 100.754
Type: Sphere length: 3.0 diff: 83.097 area: 113.097
Type: Sphere length: 4.0 diff: 171.062 area: 201.062
Type: Sphere length: 5.0 diff: 284.159 area: 314.159

11. (optional) Change the compareArea() method in Shape.java to be default instead of


static. You’ll also need to make a few tweaks inside ShapesTest.java.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 9-2: Using Static and Default Methods in Interfaces


Chapter 9 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 10:
Using the Date/Time API -
Working with Local Dates
and Times
Chapter 10

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10


Chapter 10 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 10

Practices Overview
In these practices, you will work with the new date and time API.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10


Chapter 10 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Working with local dates and times

Overview
In this practice you work with LocalDate, LocalTime and LocalDateTime objects to
provide answers to the questions asked in the practice. Local objects have no concept of a time
zone, so you can assume that all of the questions in the practice relate to the local time zone.
Also, all of the dates utilize the ISO calendar.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/10DateTimeLocal/practices/lab_10-1 directory.

Tasks

Oracle University and CCYD S.R.L. use only


1. Open the LocalDatesAndTimes project.
2. Open the Java class file, LocalDatesAndTimes, in the com.example package.
3. Read through the comments—these indicate what code you need to write to answer the
questions provided.
• Consult the lecture slides and the documentation if you get stuck.
• When you have completed, the output from your class should look similar to the
following output. (You do not need to format the print statements exactly the same
way.)
Abe was 46 when he died.
Abe lived for 16863 days.

Bennedict was born in a leap year: true


Days in the year he was born: 366
Bennedict is 3 decades old.
It was a SATURDAY on his 21st birthday.

Planned Travel time: 340 minutes


Delayed arrival time: 20:44

The flight arrives in Miami: 2014-03-24T21:30


The delayed arrival time is: 2014-03-25T01:57

School starts: 2014-09-09


School ends: 2015-06-25
Number of school days: 183

The meeting time is: 2014-02-18T13:30

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 10-1: Working with local dates and times


Chapter 10 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Working with local dates and times


Chapter 10 - Page 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 11 -
Using the Date/Time API -
Working with Time Zones
Chapter 11

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11


Chapter 11 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 11

Practices Overview
In these practices, you will work with the new date and time API.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11


Chapter 11 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Working with Dates and Times Across Time Zones

Overview
In this practice, you work with time zone classes to calculate dates and times across time
zones.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/11DateTimeTimeZone/practices/lab_11-1 directory.

Tasks
Open the NetBeans project DepartArrive.
Open the class file, DepartArrive.java, in the com.example package.

Oracle University and CCYD S.R.L. use only


Read through the comments—these indicate what code you need to write to answer the
questions provided.
• Consult the lecture slides and the documentation if you get stuck.
• When you have completed, the output from your class should look similar to the
following (Note that you need not format the print statements exactly the same way.)
Flight 123 departs SFO at: 2014-06-13T22:30-07:00[America/Los_Angeles]
Local time BOS at departure: 2014-06-14T01:30-04:00[America/New_York]
Flight time: 5 hours 30 minutes
Flight 123 arrives BOS: 2014-06-14T07:00-04:00[America/New_York]
Local time SFO at arrival: 2014-06-14T04:00-07:00[America/Los_Angeles]

Flight 456 leaves SFO at: 2014-06-28T22:30-07:00[America/Los_Angeles]


Local time BLR at departure: 2014-06-29T11:00+05:30[Asia/Calcutta]
Flight time: 22 hours
Flight 456 arrives BLR: 2014-06-30T09:00+05:30[Asia/Calcutta]
Local time SFO at arrival: 2014-06-29T20:30-07:00[America/Los_Angeles]

Flight 123 departs SFO at: 2014-11-01T22:30-07:00[America/Los_Angeles]


Local time BOS at departure: 2014-11-02T01:30-04:00[America/New_York]
Flight time: 5 hours 30 minutes
Flight 123 arrives BOS: 2014-11-02T06:00-05:00[America/New_York]
Local time SFO at arrival: 2014-11-02T03:00-08:00[America/Los_Angeles]

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 11-1: Working with Dates and Times Across Time Zones
Chapter 11 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Working with Dates and Times Across Time Zones
Chapter 11 - Page 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 12 -
Using the Date/Time API -
Working with Date and Time
Amounts
Chapter 12

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12


Chapter 12 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 12

Practices Overview
In these practices, you will work with the new date and time API.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12


Chapter 12 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-1: Formatting Dates

Overview
In this practice, you work with DateTimeFormatter.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/12DateTimeAmounts/practices/lab_12-1 directory.

Tasks
1. Open the TimeBetween project in NetBeans.

Oracle University and CCYD S.R.L. use only


2. Open the TimeBetween.java class.
3. Modify the class to read a string from the console and correctly identify the delta between
today and the entered date in years, months, and days.
• Use the appropriate method to ensure that the values for the year, month, and days
are always positive.
4. The output should look similar to this:
Enter a date: (MMMM d, yyyy): July 9, 2014
Date entered: July 9, 2014
There are 0 years, 4 months, 16 days between now and the date
entered.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 12-1: Formatting Dates


Chapter 12 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-1: Formatting Dates


Chapter 12 - Page 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 13:
Writing JavaScript with Java
Using Nashorn - Creating and
Executing Shell Scripts
Chapter 13

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13


Chapter 13 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 13

Practices Overview
In these practices, you will work with the Nashorn engine, an implementation of JSR-223,
scripting for the Java Platform and leveraging the Da Vinci project, JSR-292, supporting
Dynamically Typed Languages on the Java Platform. You will use Nashorn to execute
JavaScript files as shell scripts.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13


Chapter 13 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Creating Shell Scripts Using Nashorn Global Objects

Overview
In this practice, you create a shell script to display either files or directories using a shell.

Assumptions
You have listened to the lecture and have NetBeans setup with Java 8. You have navigated to
the /home/oracle/labs/13NashornShell/practices/lab_13-1 directory.

Tasks
1. Open NetBeans.
2. Open the Favorites Window.
3. Create a JavaScript file named list.js in your home directory.

Oracle University and CCYD S.R.L. use only


• Right-click Home and select New -> Other.
• Select Other from Categories and JavaScript file from File Types.
• Click Next.
• Enter list as the File Name and click Finish.
4. Add the shebang notation for jjs to the script.
5. Use the readLine()function to prompt the user to enter a letter, either d for directories or f
for files.
• Loop until the user enters either a "d" or "f" character.
• Store what the user enters into a inp variable.
6. Use the $EXEC global to execute the "ls -l" command into a JavaScript variable.
• Use the split command with the argument ("\n") to parse the output of the ls
command into an array of strings.
7. Iterate through the array of strings.
• If the input was "d," show only the directories—these strings begin with "d."
If the input was "f," show only the files.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 13-1: Creating Shell Scripts Using Nashorn Global Objects


Chapter 13 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Creating Shell Scripts Using Nashorn Global Objects


Chapter 13 - Page 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 14:
Writing JavaScript with Java
Using Nashorn - Writing
JavaScript Applications
Chapter 14

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14


Chapter 14 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 14

Practices Overview
In these practices, you will work with the Nashorn engine, an implementation of JSR-223,
scripting for the Java Platform and leveraging the Da Vinci project, JSR-292, supporting
Dynamically Typed Languages on the Java Platform. In this practice, you will explore how to
use Java in JavaScript using the capabilities of the Nashorn Engine.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14


Chapter 14 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-1: Creating a JavaScript Multi-Threaded Socket Server

Overview
In this practice, you will use the global Java object and some of its functions. In this practice,
you will create a multi-threaded socket listener application—the server handles connections
from multiple clients and echoes back what is sent to the server. When the client sends a "Bye"
string, the server closed the client's connection, but continues to listen for new connections.

Assumptions
You have completed the previous practice. You have navigated to the
/home/oracle/labs/14NashornApp/practices/lab_14-1 directory.

Tasks

Oracle University and CCYD S.R.L. use only


1. Open the SimpleServer project and run it.
2. Open the SimpleClient project and run it.
• Run the SimpleClient project at least twice more—each run will open a new tab in
the Output window.
• Enter text in each window to see that the server has created a thread for each client.
• Enter Bye to terminate the client connection.
• Note that the server does not quit until you manually terminate it.
3. Create a JavaScript file called Server.js.
4. Use the Java Server class as a model for creating a multithreaded server in JavaScript
code.
• Start by creating a set of JavaScript variable for the classes you know you will need:
ServerSocket, PrintWriter, OutputStreamWriter, InputStreamWriter,
BufferedReader, Thread.
• Look at the slide on extending concrete Java classes for an idea about how to
implement the run method for the threads you will spawn.
• Consider using the syntax to disambiguate which println method you use to echo
back the string from the client.
<Enhancement: Have the server keep track of connections in a hash map, and when the map is
empty, quit the server.>

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 14-1: Creating a JavaScript Multi-Threaded Socket Server


Chapter 14 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-1: Creating a JavaScript Multi-Threaded Socket Server


Chapter 14 - Page 4
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 15:
Writing JavaScript with Java
Using Nashorn - Writing
JavaFX Applications Using
JavaScript
Chapter 15

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15


Chapter 15 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 15

Practices Overview
In these practices, you will work with the Nashorn engine, an implementation of JSR-223,
scripting for the Java Platform and leveraging the Da Vinci project, JSR-292, supporting
Dynamically Typed Languages on the Java Platform. In this practice, create a JavaFX
application using JavaScript.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15


Chapter 15 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-1: Creating a JavaFX PieChart Application as a JavaScript


Application

Overview
In this practice, you rewrite an existing JavaFX application that displays a simple PieChart into a
JavaScript application.

Assumptions
You have completed the previous practices. You have navigated to the
/home/oracle/labs/15NashornJavaFX/practices/lab_15-1 directory.

Tasks
1. Open the NetBeans project PieChartFX and run the application.

Oracle University and CCYD S.R.L. use only


2. In the practices/lab_15-1 directory, create a new JavaScript file named
PieChart.js.
3. Use the PieChartFX class to model the script file.
• Similar to the HelloWorld example, begin by creating a start function that takes a
primaryStage as its argument.
• Add the necessary JavaClass types by using Java.type functions.
4. Test the PieChart.js application by using jjs.
5. (Optional) Refine the PieChart.js application.
• Remove the start function and use the $STAGE global instead of primaryStage.
• Replace the Java.type function calls with the appropriate load function calls.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 15-1: Creating a JavaFX PieChart Application as a JavaScript Application


Chapter 15 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Dynamically Changing a JavaFX Application

Overview
In this practice, you use a FileWatcher to determine when a JavaScript file has been
modified. The event will trigger an update to a running JavaFX application.

Assumptions
You have completed the previous practices. You have navigated to the
/home/oracle/labs/15NashornJavaFX/practices/lab_15-2 directory.

Tasks
1. Open the NetBeans project, PieChartDynamic.

Oracle University and CCYD S.R.L. use only


2. Open the PieChartDynamic class in the com.example package.
• This JavaFX application gets an instance of a Nashorn engine in the init method, and
calls the initFileWatcher method to launch a thread that monitors the
PieChartExample.js file. This file is in the project directory.
• The start method stores the instance of the stage passed to it and invokes the
applyConfigScript method, before showing the stage.
• The applyConfigScript method is invoked by the start method, but also whenever
there is a change to the local PieChartExample.js file.
3. Implement the applyConfigScript method.
• The method should first use the engine instance to evaluate the script contained in the
Path object script.
• Create an instance of an Invocable object.
• Using the Invocable instance, invoke the init function and pass the
primaryStage as a parameter to the function.
4. Run the PieChartDynamic application.
• The Pie chart example should display.
5. Modify the PieChartExample.js script to dynamically change the JavaFX application.
• Click the Files tab in NetBeans and expand the PieChartDynamic project.
• Open PieChartExample.js in NetBeans.
• Change the file by uncommenting the line that sets the chart labels visibility and save
the file.
• You should immediately see a change in the running JavaFX application.
• Add a chart data element after the Dell element:
new PieChart.Data("Sun", 15),
• Save the file again.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 15-2: Dynamically Changing a JavaFX Application


Chapter 15 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 16:
Mission Control
Chapter 16

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Overview


Chapter 16 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 16: Overview

Practice Overview
In these practices, you explore techniques for monitoring the JVM garbage collection with
Mission Control.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Overview


Chapter 16 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-1: The Mission Control General Page

Overview
In this practice, review the key features and information available in the Oracle Mission Control
General page.

Assumptions
Java 8 with Mission Control is in your path. You have listened to the lecture portion of this
lesson and have seen a demonstration of the user interface.

Tasks
1. Open the Java2D project in the practices directory for this lesson.
2. Run the project. A graphics application should load.

Oracle University and CCYD S.R.L. use only


3. Click the Transforms tab.
4. Open Terminal.
5. Create at least two tabs.
6. In one tab, start Mission Control:
jmc &
7. On the first load, the Welcome Screen may be displayed. Just close this tab to see the JVM
Browser.
8. Once Mission Control loads, you should see three JVMs under the JVM Browser tab. One
entry is for Mission Control, one for NetBeans, and the other for Java2Demo.
9. Right-click the Java2Demo JVM and select Start JMX Console. The General page should
load on the screen.
Notice the three dials at the top of the screen. Note also the two graphs on the screen.
10. Click the System tab.
Note the type of information displayed on the tab: information about the operating system,
hardware, and memory.
11. Click the Overview tab to return to the default view.
12. Add a dial to monitor machine CPU usage.
a. Click the green plus on the Dashboard panel.
b. The Select Attributes to Add dialog box is displayed.
c. Navigate down to the Operating System section.
d. Select the SystemCpuLoad attribute.
e. Leave all the other settings at their default values. Click Finish.
A dial showing the CPU load for the entire system is now part of the Dashboard panel.
13. Add a new graph panel to the Overview tab.
a. Click the green plus sign at the top of the Overview tab.
b. A new chart is added at the bottom of the page. Notice that the chart is named "My
Chart 1" and that it does not yet contain any data.
c. Click the Green Plus button for the chart.
d. Select the following values: java.lang > MemoryPool > Eden Space > Usage > used.
You can now see the amount of memory used by the eden space in real time.
e. Click Finish.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-1: The Mission Control General Page


Chapter 16 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

14. Take a moment to observe the updated user interface.


15. Reset the user interface to its original settings.
a. Mouse up to the top of the Overview tab.
b. Mouse over the yellow left arrow. This button resets the user interface to its default
values.
c. Click the yellow arrow.
d. A confirmation dialog box is displayed. Click OK.
The user interface is returned to its default value.
16. Try to create your own dial and graph. Repeat the preceding steps but select attributes of
your choosing.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-1: The Mission Control General Page


Chapter 16 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-2: Mission Control MBeans Page

Overview
In this practice, explore the key features and information available on the Oracle Mission Control
MBeans page.

Assumptions
Java 8 with Mission Control is in your path. You have listened to the lecture portion of this
lesson and have seen a demonstration of the user interface.

Tasks
1. Continue using the NetBeans application and Mission Control Console from the last
practice.

Oracle University and CCYD S.R.L. use only


2. Click the MBeans Browser tab to display the MBeans page.
3. Select an attribute to chart.
a. Open java.lang > MemoryPool > Eden Space > Usage > used.
b. Right-click the value and select Visualize.
c. In the Create Chart dialog box, click Add Chart.
Note: You can add attributes to existing charts from this interface.
d. Click OK.
e. Click the Overview tab and review the chart that you just created.
f. Click the MBeans Browser tab to return to the MBeans page.
4. Export data from an attribute.
a. Return to the Eden Space attribute. Open java.lang > MemoryPool > Eden Space.
b. Right-click the menu and select Clipboard Settings.
c. Make sure that Copy as CSV is selected.
d. Right-click the table and select Copy.
e. Open a text editor.
f. Copy the data into a text editor. Examine the data.
g. Return to the MBeans page.
5. View VM options by using the Operations tab.
a. Click the Operations tab.
b. Open com.sun.management, select HotSpotDiagnostic, and then select
getVMOption.
c. Enter the following in the value field: ThreadStackSize
d. Click the Execute button. The value set for that option in the JVM should be displayed.
e. Enter the following: MaxTenuringThreshold
f. Click the Execute button. The value set for that option in the JVM should be displayed.
g. Select the setVMOption.
h. Enter the following values for p0 and p1: PrintGCDetails, true
i. Click Execute. The PrintGCDetails option is now turned on.
j. Switch to the NetBeans app where you started Java2Demo. You should not see the
output from PrintGCDetails.
k. Switch back to the MBeans page in Mission Control.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-2: Mission Control MBeans Page


Chapter 16 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

l. Turn off PrintGCDetails using the values: PrintGCDetails, false


6. Turn on a Notification for this JVM.
a. Select com.sun.management > GarbageCollectionAggregator in the MBean Tree.
b. Click the Notifications tab.
c. Select com.sun.management.gc.notification.
d. Select the Subscribe box.
e. Wait for two or three events to occur.
f. Deselect the Subscribe button.
g. Examine the data that was collected.
7. Examine the Metadata tab.
a. Click the MetaData tab.
b. Examine the Metadata displayed for each attribute.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-2: Mission Control MBeans Page


Chapter 16 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-3: Mission Control Triggers Tab

Overview
In this practice, explore the key features and information available on the Oracle Mission Control
Runtime page.

Assumptions
Java 8 with Mission Control is in your path. The Java 8 demos are installed on the system. You
have listened to the lecture portion of this lesson and have seen a demonstration of the user
interface.

Tasks
1. Set Triggers for the JVM.

Oracle University and CCYD S.R.L. use only


a. Click the Overview page button.
b. Observe the JVM CPU usage. Note the lowest levels of CPU usage by the JVM.
c. Select the Triggers tab.
d. Select CPU Usage - JVM Process (Too Low).
e. Review the Rule Details information under Description.
f. Set the minimum trigger value based on your earlier observations. For example, to set
the trigger value to 9%.
g. Click the Action tab. Review all the options available to you.
h. Click the Constraints tab. Notice the date and time ranges that you can set here.
i. Enable the CPU Usage - JVM Process (Too Low) trigger.
j. Observe the events that are triggered.
k. Click the Alert button to review information about the triggered event.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-3: Mission Control Triggers Tab


Chapter 16 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

l. After a few events are triggered, disable the trigger.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-3: Mission Control Triggers Tab


Chapter 16 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-4: Mission Control Other Tabs

Overview
In this practice, explore the key features and information available on the Oracle Mission Control
Runtime page.

Assumptions
Java 8 with Mission Control is in your path. The Java 8 demonstrations are installed on the
system. You have listened to the lecture portion of this lesson and have seen a demonstration
of the user interface.

Tasks
1. Explore the System tab.

Oracle University and CCYD S.R.L. use only


a. Click the System tab.
b. The System tab is displayed. Note the information that is displayed.
c. The System Properties panel allows you to filter and search the JVM system
properties.
d. Enter OS in the filter dialog box.
e. Note that the values displayed contain OS in the name.
2. Explore the Memory tab.
a. Click the Memory tab.
Note the information displayed. Some of the data is similar to the data on the
Overview tab but with a little more detail about the size of memory in the JVM and the
system.
3. Explore the Threads tab.
a. Click the Threads tab.
The Threads tab provides detailed information about threads in the system. All the
columns are sortable. Note that you can turn on three options to provide more
information about the threads.
b. Enable CPU profiling.
c. Sort by Total CPU Usage. Note which threads are using the most CPU time.
d. Enable Deadlock Detection. There are no deadlocks in this application.
e. Enable Allocation.
f. Sort the threads by memory size. Note which methods are using the most memory.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 16-4: Mission Control Other Tabs


Chapter 16 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-4: Mission Control Other Tabs


Chapter 16 - Page 10
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and CCYD S.R.L. use only


Practices for Lesson 17: Java
Flight Recorder
Chapter 17

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson: Overview


Chapter 17 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson: Overview

Practice Overview
In these practices, you will explore Java Flight Recorder.

Oracle University and CCYD S.R.L. use only

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson: Overview


Chapter 17 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 17-1: Starting a JFR Recording from Mission Control

Overview
In this practice, you start and record a Java Flight Recorder Session from the Oracle Mission
Control JVM Browser page.

Assumptions
Java 8 with Mission Control is in your path. The Java 8 demonstrations are installed on the
system. You have listened to the lecture portion of this lesson and have seen a demonstration
of the user interface.

Tasks
1. Open the Java2D project in the practices directory for this lesson.

Oracle University and CCYD S.R.L. use only


2. Run the project. A graphics application should load.
3. Click the Transforms tab.
4. Open Terminal.
5. Create at least two tabs.
6. In one tab, start Mission Control:
jmc &
7. Find Java2Demo in the JVM browser.
8. Expand the arrow next to the JVM to show the options available.
9. Expand the arrow next to Flight Recorder to see that there are currently no flight recordings.
10. Right-click the Flight Recorder and select Start Flight Recording.
11. Set the recording time to 5 minutes.
12. Select Profiling - on server as the Template.
13. Click the Next button. A list of settings for this session is displayed.
14. Change the Garbage Collection options to All.
15. For the exceptions option, change the value to All exceptions, including errors.
16. Make sure that the Heap Statistics, Class Loading, and Allocation Profiling check
boxes are selected.
17. Click Next.
18. Open Expand Java Application.
19. Select Java Exception.
20. Make sure that the Enabled check box is selected.
21. Click Finish.
22. Click various tabs on Java2Demo to vary the results a bit. After five minutes, the recording
should be complete.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 17-1: Starting a JFR Recording from Mission Control


Chapter 17 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 17-2: Reviewing the Java Flight Recorder General Tab Group

Overview
In this practice, review a Java Flight Recorder Session from the Oracle Mission Control JVM
Browser page. If you followed the steps in the previous practice, the recording should be loaded
into your Mission Control console.

Assumptions
Java 8 with Mission Control is in your path. You have listened to the lecture portion of this
lesson and have seen a demonstration of the user interface. You have completed the previous
practice.

Tasks

Oracle University and CCYD S.R.L. use only


1. With the flight recording loaded, the General Tab Group is shown with the Overview tab
shown by default.
• Performance dials are shown at the top of the page. Status for average and max are
shown for Heap Usage, Total CPU Usage, and GC Pause Time.
• Under the dials are two tabs, CPU Usage and Heap Usage.
Note: The check boxes allow you to view or hide the graph elements.
• Click the Heap Usage tab. A graph of Committed Heap and Used Heap is displayed.
Options to display or not display the graphs are available.
• The General section shows JVM and OS information about this recording.
2. Click the JVM Information tab. More detailed information about the JVM is displayed,
including the command-line options used to start the JVM.
3. Click the System Properties tab. This shows all the properties set on that JVM.
4. Filter for vm-related information.
a. Click the Filter Column text box under System Properties at JVM Start.
b. Type: *vm
Note that only Key information with “vm” in the name is displayed.
c. Clear the text that you typed.
The list of System Properties should be reset to its starting values.
5. Filter for “vm” by using Regular Expressions.
a. Click the Filter Column text box under System Properties at JVM Start.
b. Type: RegExp: .*vm.*
c. Note that only Key information with 'vm' in the name is displayed.
Note: If you type text that is not a correct regular expression, the text box is displayed
in red.
d. Clear the text you typed.
The list of System Properties should be reset to their starting values.
6. Click the Recording tab.
a. Review Event Settings in the middle of the page.
b. Scroll through the values to which options were enabled; note the Threshold values
from some of the options.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 17-2: Reviewing the Java Flight Recorder General Tab Group
Chapter 17 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 17-3: Reviewing the Java Flight Recorder Memory Tab Group

Overview
In this practice, review a Java Flight Recorder Session from the Oracle Mission Control JVM
Browser page. Continue with the recording from the previous practice.

Assumptions
Java 8 with Mission Control is in your path. You have listened to the lecture portion of this
lesson and have seen a demo of the user interface. You have completed the previous practice.

Tasks
1. Click the Memory tab group in the JFR user interface. Note the general memory-related
information displayed.

Oracle University and CCYD S.R.L. use only


2. Click the Garbage Collections tab.
3. Review the Heap graph at the top of the page.
The default graph shows two graphs. The heap memory used is superimposed with the
pause times for garbage collection.
a. Note that each data set on the graph can be unchecked. Uncheck and recheck some
of the items on the graph.
b. Note the four subtabs (Heap, Reference Objects, Failed Promotions, and Failed
Evacuations) above the Heap graph.
c. Click each tab to see what information is displayed in the graph.
d. Return to the Heap tab when you are done.
4. Review the Garbage Collection Table. Note that this table contains all the garbage
collections that occurred during the recording. The table is sortable.
a. Sort the Garbage Collections table by Longest Pause. In effect, click the Longest
Pause column until the longest pauses appear at the top of the table.
b. Click the GC with the longest pause time (generally, this should be an old generation
collection, SerialOld). Notice that doing this populates the five tabs to the right.
c. Click each of the GC-related tabs and review the information in them. For example, the
Heap tab shows the size of the heap before and after GC.
d. Sort the Garbage Collections table for the shortest pause.
e. Click the shortest garbage collection (it should be a minor GC, DefNew) and review the
information about that GC.
5. Click the GC Times tab and review the range navigator features.
a. Note that only GC Pause times are shown in this graph.
b. Identify a high-activity area in the range navigator.
c. Grab the left and right sides of the Range Navigator so that they are focused on the
area of interest.
d. Select the Synchronize Selection check box in the upper-right corner of the page.
e. Notice how the graph changes. Also the number of GCs changes. Note that the time
interval is now different.
f. Under the range navigator, mouse over each of the control buttons. A pop up should
describe the function of each button.
g. Click the Garbage Collections tab. Notice how that data has changed as well. This is
due to your select of the synchronize option.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 17-3: Reviewing the Java Flight Recorder Memory Tab Group
Chapter 17 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

h. Click the GC Times tab.


i. Reset the range by clicking the Select All button under the range navigator, or by
double-clicking the range navigator.
6. Click the GC Configuration tab. Note the data displayed on the page.
7. Click the Allocations tab.
a. Note that there are three tabs right under the range navigator.
b. Click the Allocation in new TLAB tab. Review the data displayed.
c. Click the Allocation outside the TLAB tab. Review the data displayed.
8. Click the Object Statistics tab.
a. Note that the Heap Contents table shows the amount of heap memory used by
various objects.
b. Note that the Top Growers table shows which objects have increased in size the most

Oracle University and CCYD S.R.L. use only


from the start of the recording to the end of the recording. This could be a very useful
tool for finding memory leaks.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 17-3: Reviewing the Java Flight Recorder Memory Tab Group
Chapter 17 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 17-4 Reviewing the Java Flight Recorder Code Tab Group

Overview
In this practice, review a Java Flight Recorder Session from the Oracle Mission Control JVM
Browser page. Continue with the recording from the previous practice.

Assumptions
Java 8 with Mission Control is in your path. The Java 8 demonstrations are installed on the
system. You have listened to the lecture portion of this lesson and have seen a demonstration
of the user interface. You have completed the previous practice.

Tasks
1. Click the Code Tab Group. Note that the hot packages and classes for your application are

Oracle University and CCYD S.R.L. use only


displayed.
2. Click the Hot Methods tab. Note that the methods that the application spends the most
significant amount of time executing are displayed.
a. Click one of the methods displayed. This should populate the Predecessor and
Successor tabs. The Predecessor tab shows all methods executed before this method.
The Successor tab showed all the methods executed after this method.
3. Click the Call Tree tab. This tab shows stack traces for entry point methods like start() and
main().
4. Click the Exceptions tab.
a. Notice that Information about Exceptions encountered during the recording is
displayed.
b. Select an exception. This populates the Stack Trace table where you can look at the
stack trace for that exception.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practice 17-4 Reviewing the Java Flight Recorder Code Tab Group
Chapter 17 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 17-4 Reviewing the Java Flight Recorder Code Tab Group
Chapter 17 - Page 8
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Oracle University and CCYD S.R.L. use only

You might also like