Java Reference
In-Depth Information
public String toString() {
return name;
}
public enum Type { MEAT, FISH, OTHER }
}
We'll now explore how you can use the Streams API in more detail. We'll compare streams to
collections and provide some background. In the next chapter, we'll investigate in detail the
stream operations available to express sophisticated data processing queries. We'll look at many
patterns such as filtering, slicing, finding, matching, mapping, and reducing. There will be many
quizzes and exercises to try to solidify your understanding.
Next, we'll discuss how you can create and manipulate numeric streams, for example, to
generate a stream of even numbers or Pythagorean triples! Finally, we'll discuss how you can
create streams from different sources such as from a file. We'll also discuss how to generate
streams with an infinite number of elements—something you definitely can't do with collections!
4.2. Getting started with streams
We start our discussion of streams with collections, because that's the simplest way to begin
working with streams. Collections in Java 8 support a new stream method that returns a stream
(the interface definition is available in java.util.stream.Stream). You'll later see that you can also
get streams in various other ways (for example, generating stream elements from a numeric
range or from I/O resources).
So first, what exactly is a stream ? A short definition is “a sequence of elements from a source
that supports data processing operations.” Let's break down this definition step by step:
Sequence of elements Like a collection, a stream provides an interface to a sequenced set of
values of a specific element type. Because collections are data structures, they're mostly about storing
and accessing elements with specific time/space complexities (for example, an ArrayList vs. a
LinkedList ). But streams are about expressing computations such as filter , sorted , and map that
you saw earlier. Collections are about data; streams are about computations. We explain this idea in
greater detail in the coming sections.
Source Streams consume from a data-providing source such as collections, arrays, or I/O resources.
Note that generating a stream from an ordered collection preserves the ordering. The elements of a
stream coming from a list will have the same order as the list.
 
Search WWH ::




Custom Search