Stream API

Java 8 introduced the new stream API , which allows collections to be processed in a functional style.

int digits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Arrays.stream(digits)
        .filter(i -> i % 2 == 0)
        .map(i -> i * i)
        .forEach(i -> System.out.println(i));

IntStream.of(0,1,2,3,5,6,7,8,9)
        .reduce( (result, i) -> result+=i)
        .ifPresent((i)-> System.out.println(i));

Stream does not store any data. It gets elements from a source such as a data structure (for example map), an array, a generator function, or an I/O channel. Important that source does not changed by stream.

Intermediate operations return a new stream. They are always lazy. For example, filter() does not actually perform any filtering, but generates a predicate that will be used when traversing.

Terminal operations may traverse over elements and produce some result. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used. In some cases, the stream pipeline will not be executed if the result can be obtained in another simple way. For example, when you want compute count of element when source of stream is collection.

There are two types of streams: sequential and parallel. Parallelism allows effectively use CPU cores, but not in all cases, for example when collection has small number of elements. On a single core machine parallel streams always perform worse than sequential streams in cause of the management overhead. Parallel streams do not magically solve synchronization problems. So, you must sure that predicates and functions used in the process are thread-safe.

Stream interface

method description
static methods
builder() Returns a builder for a Stream.
empty() Returns an empty sequential Stream.
generate(supplier) Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
of(el) Returns a sequential Stream containing a single element.
of(...el) Returns a sequential ordered stream whose elements are the specified values.
concat(s1, s2) Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
intermediate operations
map(mapper) Returns a stream consisting of the results of applying the given function to the elements of this stream.
sorted() Returns a sorted stream.
sorted(cmpr) Returns a stream sorted by the specified comparator.
filter( predicate) Returns a filtered stream. All elements of new stream will be match to the given predicate.
distinct() Returns a stream consisting of the distinct elements of this stream.
takeWhile( predicate) Returns new stream by taking elements from the initial stream while the predicate holds true. It differ from filter(), that checks all elements. And takeWhile () stops checking after the first false predicate.(Since Java 9)
dropWhile( predicate) Returns new stream by removing elements from the initial stream while the predicate holds true. It differ from filter(), that checks all elements. And dropWhile () stops checking after the first false predicate. (Since Java 9)
skip(n) Returns new stream without first n elements.
peek(action) Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
flatMap( mapper) Returns a new stream where elements will be produced by given mapper.
flatMapToDouble( mapper) Returns a DoubleStream consisting of the results of mapping each element of this stream to double value.
flatMapToInt( mapper) Returns an IntStream consisting of the results of mapping each element of this stream to int value.
flatMapToLong( mapper) Returns an LongStream consisting of the results of mapping each element of this stream to long value.
terminal operations
forEach(action) Performs an action for each element of this stream.
findFirst() Returns an Optional object with first element or empty. If the stream has no encounter order, then any element may be returned.
findAny() Returns an Optional object with any element. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream.
reduce(accum) Reduces the elements of a stream to a single value. There are special cases of reduction: count()/min()/max().
count() Returns the count of elements in this stream.
max(cmpr) Returns the maximum element using specified comparator.
min(cmpr) Returns the minimum element using specified comparator.
collect(collector) Returns the result of the intermediate operations performed on the stream.
anyMatch( predicate) Returns whether any elements of this stream match the provided predicate.
allMatch( predicate) Returns whether all elements of this stream match the provided predicate.
toArray() Returns an array containing the elements of this stream.

stream creation

Ways to create a stream:

  • from factory methods of the Stream interface (see static methods above)
  • from methods of the Collection inteface
    • stream()
    • parallelStream()
  • from factory method of the Arrays util class
    • stream()
  • from the BufferedReader method
    • lines()
try (BufferedReader reader = new BufferedReader(new FileReader("ddd"))) {
    reader.lines().forEach(System.out::println);
} catch (Exception e) {
    e.printStackTrace();
}