Java Reference
In-Depth Information
Chapter 4. Introducing streams
This chapter covers
What is a stream?
Collections vs. streams
Internal vs. external iteration
Intermediate vs. terminal operations
Collections is the most heavily used API in Java. What would you do without collections? Nearly
every Java application makes and processes collections. Collections are fundamental to many
programming tasks: they let you group and process data. To illustrate collections in action,
imagine you want to create a collection of dishes to represent a menu and then iterate through it
to sum the calories of each dish. You may want to process the collection to select only
low-calorie dishes for a special healthy menu. But despite collections being necessary for almost
any Java application, manipulating collections is far from perfect:
Much business logic entails database-like operations such as grouping a list of dishes by category (for
example, all vegetarian dishes) or finding the most expensive dish. How many times do you find
yourself reimplementing these operations using iterators? Most databases let you specify such
operations declaratively. For example, the following SQL query lets you select the names of dishes that
are low in calories: SELECT name FROM dishes WHERE calorie < 400 . As you can see, you
don't need to implement how to filter using the attributes of a dish (for example, using an iterator and
an accumulator). Instead, you express only what you expect. This basic idea means that you worry less
about how to explicitly implement such queries—it's handled for you! Why can't you do something
similar with collections?
How would you process a large collection of elements? To gain performance you'd need to process it in
parallel and leverage multicore architectures. But writing parallel code is complicated in comparison
to working with iterators. In addition, it's no fun to debug!
So what could the Java language designers do to save your precious time and make your life
easier as programmers? You may have guessed: the answer is streams .
4.1. What are streams?
Streams are an update to the Java API that lets you manipulate collections of data in a
declarative way (you express a query rather than code an ad hoc implementation for it). For now
 
Search WWH ::




Custom Search