The Stream class and its use
The Stream
class provides the primary support for the stream concept in Java. However, there are specialized classes, such as the DoubleStream
, IntStream
, and LongStream
classes, that handle numbers. In addition, the Collection
interface supports the creation of streams.
A stream will support either a finite or an infinite sequence of elements. The methods of a stream can be classified in a number of ways such as mapping, filtering, and sorting type methods. We will start with a simple example of a stream, and then follow up with a discussion of how they are created and several of their methods.
Let's assume that we need to process an array of numbers by summing the values of each unique element. For example, in the following array, there are six distinct numbers whose sum is 35:
int[] numbers = {3,6,8,8,4,6,3,3,5,6,9,4,3,6};
One approach to solve the problem involves:
Finding the distinct numbers in the array.
Summing these numbers.
Finding the distinct numbers...