0% found this document useful (0 votes)
2 views51 pages

Lecture10 1

Lecture 10-1 of ICS 45J covers stream processing in Java, focusing on concepts such as producing streams, collecting results, and stream transformations using lambda expressions. Key topics include the immutability and lazy processing of streams, the use of the Optional type to handle absent values, and various stream operations like filter and map. The lecture also includes announcements regarding office hours and the final exam schedule.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

Lecture10 1

Lecture 10-1 of ICS 45J covers stream processing in Java, focusing on concepts such as producing streams, collecting results, and stream transformations using lambda expressions. Key topics include the immutability and lazy processing of streams, the use of the Optional type to handle absent values, and various stream operations like filter and map. The lecture also includes announcements regarding office hours and the final exam schedule.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

ICS 45J: Programming in Java

Lecture 10-1
Stream Processing, Part 1

Emily Navarro
Announcements

• I will hold office hours today (1-2pm) instead of


Thursday
• No late passes can be requested for lab 10
• Complete the ICS final evals for 0.5% extra credit
• You should have received an email about it with a deadline
• Final exam is on Thursday 3/20 8-10am
• 25 multiple-choice questions
• Covers all material since Exam 2
PART 1
Canvas Participation Quiz

Lecture 10-1: Lecture


9-1 Review

Text questions to (562) 684-


Last Time

• User-interface events include key presses, mouse moves, button


clicks, menu selections, etc.
• An event listener’s (ActionListener) methods describe the
actions to be taken when an event occurs
• UI components are arranged by placing them inside containers
• Each container has a layout manager that directs the
arrangement of its components
• Use a JTextField for reading a single line of input, a JLabel next
to each text field, and a JTextArea to show multiple lines of text
• Use radio buttons for a small set of mutually exclusive choices, a
check box for a binary choice, or a combo box for a large set of
choices
• A frame contains a menu bar, which contains menus, which
contains submenus and menu items
Text questions to (562) 684-
PART 2
Learning Objectives

• To be able to develop filter/map/reduce


strategies for solving data processing problems
• To convert between collections and streams
• To use function objects for transformations and
predicates
• To work with the Optional type

Text questions to (562) 684-


Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Streams - Overview

• Streams process data by specifying actions


• Library implements the actions using lazy execution
• Can skip steps that aren’t needed
• Can split work over multiple processors

Text questions to (562) 684-


The Stream Concept

• Algorithm for counting matches:


List<String> wordList = . . .;
long count = 0;
for (String w : wordList) {
if (w.length() > 10) { count++; }
}

• With the Java 8 stream library:


Stream<String> words = . . .;
long count = words
.filter(w -> w.length() > 10)
.count();
• You tell what you want to achieve (Keep the long strings, count them)
• You don’t dwell on the how (visit each element in turn, if it is long,
increment a variable)
• “What, not how” is powerful:
• Operations can occur in parallel
• The data can be anywhere (e.g., distributed “big data”)
Text questions to (562) 684-
Some Facts About Streams

• Streams are similar to collections, but…


• They don’t store their own data
• The data comes from elsewhere
• From a collection, a file, a database, data from the internet, …
• Streams were designed to work well with lambda
expressions:
stream.filter(w -> w.length() > 10)

• Streams are immutable


• Methods such as filter produce new streams
• Stream processing is lazy

Text questions to (562) 684-


Lazy Processing
• Suppose you ask for only five long words (not all)
• Here is how to get the first five:
Stream<String> fiveLongWords = words
.filter(w -> w.length() > 10)
.limit(5)

• Bad approach: first generate all long words, then throw most of them away
• Fortunately, stream processing is not bad, but lazy
• Works “backwards” and only computes what is necessary
• limit(5) needs an element…
• …and filter(…) examines element until it finds one
• That repeats four times
• And then… nothing
• The other stream elements never get examined

Text questions to (562) 684-


Demo: StreamDemo.java

Text questions to (562) 684-


Canvas Participation Quiz

Lecture 10-1: The


Stream Concept

Text questions to (562) 684-


PART 3
Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Producing Streams (I)

• In order to process streams, you first need to have one


• Simplest way: the of method:
Stream<String> words = Stream.of("Mary", "had", "a", "little", "lamb");
Stream<Integer> digits = Stream.of(3, 1, 4, 1, 5, 9);

• Also works for arrays:

Integer[] digitArray = { 3, 1, 4, 1, 5, 9 };
Stream<Integer> digitStream = Stream.of(digitArray);
• This is a stream of Integer objects
• Any collection can be turned into a stream:

List<String> wordList = new ArrayList<>();


Stream<String> words = wordList.stream();

Text questions to (562) 684-


Producing Streams (II)

• Several utility methods yield streams:


String filename = . . .;
try (Stream<String> lineStream = Files.lines(Paths.get(filename))) {
...
} // File is closed here

• You can make infinite streams:


Stream<Integer> integers = Stream.iterate(0, n -> n + 1);

• You can turn any stream into a parallel stream


• Causes operations to be distributed over the available processors
Stream<String> parStream = lineStream.parallel();

Text questions to (562) 684-


Canvas Participation Quiz

Lecture 10-1:
Producing Streams

Text questions to (562) 684-


PART 4
Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Collecting Results

• When you are done transforming a stream (e.g., with filter), you
want to harvest results
• Some methods (e.g., count, sum) yield a single value, others yield
a collection
• Here is how
String[] resultto
= collect into an array:
stream.toArray(String[]::new);

• String[]::new is a constructor reference (to the array constructor)


• To collect into
List<String> a List
result or Set, use collect:
= stream.collect(Collectors.toList());
Set<String> result = stream.collect(Collectors.toSet());

• A stream of strings can be collected into a single string:


String result = words.collect(Collectors.joining(", "));
// Stream elements separated with commas
Text questions to (562) 684-
Canvas Participation Quiz

Lecture 10-1:
Collecting Results

Text questions to (562) 684-


PART 5
Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Life Cycle of a Stream

• Create stream
• Transform stream (possibly multiple times)
• Collect results

Text questions to (562) 684-


Stream Transformations - map

• map transforms a stream by applying a function to each element


• Turn all words into lowercase:

Stream<String> words = Stream.of("A", "Tale", "of", "Two", "Cities");


Stream<String> lowerCaseWords = words.map(w -> w.toLowerCase());
// "a", "tale", "of", "two", "cities"

• Remove vowels from all words:


Stream<String> consonantsOnly = lowerCaseWords.map(
w -> w.replaceAll("[aeiou]", ""));
// "", "tl", "f", "tw", "cts"

• Get the length of each element:

Stream<Integer> consonantCount = consonantsOnly.map(


w -> w.length());
// 0, 2, 1, 2, 3
Text questions to (562) 684-
More Stream Transformations (I)

• Applying map yields a stream with the same number of elements


• filter only retains matching elements:
Stream<String> aWords = words.filter(w -> w.substring(0, 1).equals("a"));
// Only the words starting with "a"

• limit takes the first n:


Stream<String> first100aWords = aWords.limit(100);

• skip takes all but the first n:

Stream<String> allButFirst100aWords = aWords.skip(100);

Text questions to (562) 684-


More Stream Transformations (II)

• distinct yields a stream with duplicates removed:


Stream<String> words = Stream.of(
"how much wood could a wood chuck chuck".split(" "));
Stream<String> distinctWords = words.distinct();
// "how", "much", "wood", "could", "a", "chuck"
• sorted yields a new stream in which the elements are sorted:

Stream<String> sortedWords = distinctWords.sorted();


// "a", "chuck", "could", "how", "much", "wood"

• Element type must be Comparable


• Or supply a comparator:
distinctWords.sorted((s, t) -> s.length() – t.length())

Text questions to (562) 684-


Demo: StreamDemo2.java

Text questions to (562) 684-


Common Error: Don’t Use a Terminated Stream

• Once you apply a terminal operation, a stream is “used up”


• Can no longer apply any stream operations
• Easy mistake if you have a reference to an intermediate stream:

Stream<String> stream = list.stream();


List<String> result1 = stream.limit(50).collect(Collectors.toList());
// Save the first fifty
stream = stream.skip(50);
// Error—the stream can no
longer be used
• Instead, you would need two streams:
List<String> result1 = list.stream()
.limit(50)
.collect(Collectors.toList()); // This stream can no longer be used
List<String> result2 = list.stream() // Create another stream
.skip(50)
.limit(50)
.collect(Collectors.toList());

Text questions to (562) 684-


Canvas Participation Quiz

Lecture 10-1: Stream


Transformations

Text questions to (562) 684-


PART 6
Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


Lambda Expressions (I)

• You have seen lambda expressions in filter and map methods such as:
w -> w.length() > 10

• Like a static function


• Left side of -> operator is a parameter variable
• Right side is code to operate on the parameter and compute a result
• When used with a type like Stream<String>, compiler can determine type
• Otherwise, you can specify the type:
(String w) -> w.length() > 10

• Multiple parameters are enclosed in parentheses:

(v, w) -> v.length() - w.length()


• To use the sorted method in the Stream class to sort strings by length:
Stream<String> sortedWords = distinctWords.sorted( (v, w) -> v.length() - w.length());
// "a", "how", "much", "wood", "could", "chuck"
Lambda Expressions (II)

• Enable you to create methods that can be treated as


data
• You can:
• Pass lambdas as arguments to other methods
• Assign lambda expressions to variables for later use
• Return lambda expressions from methods
• Lambdas and streams enable you to combine many
benefits of functional programming techniques with the
benefits of object-oriented programming
Text questions to (562) 684-
Canvas Participation Quiz

Lecture 10-1: Lambda


Expressions

Text questions to (562) 684-


PART 7
Agenda

• The Stream Concept


• Producing Streams
• Collecting Results
• Stream Transformations
• Lambda Expressions
• The Optional Type

Text questions to (562) 684-


The Optional Type

• In Java, it is common to use null to denote absence of result


• Drawback: NullPointerException when programmer forgets to check
String result = oldFashionedMethod(searchParameters);
// Returns null if no match
int length = result.length();
// Throws a
NullPointerException when
• Stream
result library
is nulluses Optional type when a result may not be present
• Example: First string of length > 10:
words.filter(w -> w.length() > 10).findFirst()

• What if there is none? An Optional<String> either contains a string or an


indication that no value is present

Optional<String> optResult = words


.filter(w -> w.length() > 10)
.findFirst();

Text questions to (562) 684-


Working With Optional

• Work with it, not against it (That is, don’t treat it like a potentially
null reference)
• orElse extracts the value or an alternative if there is none:
int length = optResult.orElse("").length();

• ifPresent passes on the value to a function; does nothing if there


optResult.ifPresent(v -> results.add(v));
is none:

• Ififneither of these works,


(optResult.isPresent()) { use isPresent to test if there is a value
and get to get it:
System.out.println(optResult.get());
}
else {
System.out.println("No element");
}

Text questions to (562) 684-


Returning Optional

• Declare return type as Optional<T>


• If there is a result, return Optional.of(result)
• Otherwise return Optional.empty()
public static Optional<Double> squareRoot(double x) {
if (x >= 0) {
return Optional.of(Math.sqrt(x));
}
else {
return Optional.empty();
}
}

Text questions to (562) 684-


Canvas Participation Quiz

Lecture 10-1: The


Optional Type

Text questions to (562) 684-


Summary

• A stream is an immutable sequence of values that are processed


lazily
• The Stream.of static method and the stream methods of collection
classes yield streams
• You can transform streams into a form from which you can collect
results using the map and filter methods
• A lambda expression consists of one or more parameter variables,
an arrow ->, and an expression or block yielding the result
• The Optional class is a wrapper for objects that may or may not be
present

Text questions to (562) 684-


Announcements

• I will hold office hours today (1-2pm) instead of


Thursday
• No late passes can be requested for lab 10
• Complete the ICS final evals for 0.5% extra credit
• You should have received an email about it with a deadline
• Final exam is on Thursday 3/20 8-10am
• 25 multiple-choice questions
• Covers all material since Exam 2

You might also like