Lecture10 1
Lecture10 1
Lecture 10-1
Stream Processing, Part 1
Emily Navarro
Announcements
• 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
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:
Lecture 10-1:
Producing Streams
• 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);
Lecture 10-1:
Collecting Results
• Create stream
• Transform stream (possibly multiple times)
• Collect results
• You have seen lambda expressions in filter and map methods such as:
w -> w.length() > 10
• 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();