Search

Terminating operations , Collectors - java 8 features

Usually, dealing with a stream will involve these steps:
  1. Obtain a stream from some source.
  2. Perform one or more intermediate operations, like filter, map, etc.
  3. Perform one terminal operation.
A terminal operation must be the final operation invoked on a stream. Once a terminal operation is invoked, the stream is “consumed” and is no longer usable.
There are several types of terminal operations available:
  • reducers like reduce(..)count(..)findAny(..)findFirst(..) terminate stream processing. Depending on the intention, the terminal operation can be a short-circuiting one. For instance, findFirst(..) will terminate the stream processing as soon as it encounters a matching element.
  • collectors, as the name implies, are for collecting the processed elements into a resulting collection.
  • forEach performs some action for each element in the stream.
  • iterators are the good ‘ol way to work with collections if none of the options above satisfies our needs.

Collectors


While stream abstraction is continuous by its nature, we can describe the operations on streams but to acquire the final results we have to collect the data somehow. The Stream API provides a number of so-called “terminal” operations. The collect() method is one of the terminal operations that allow us to collect the results:
List students = persons.stream()
    .filter(p -> p.getAge() > 18)
    .map(Adult::new)
    .collect(new Collector<Student, List>() { ... });
Fortunately, in most cases you wouldn’t need to implement the Collector interfaces yourself. Instead, there’s a Collectors utility class for convenience:
List students = persons.stream()
    .filter(p -> p.getAge() > 18)
    .map(Student::new)
    .collect(Collectors.toList());
Or in case if we would like to use a specific collection implementation for collecting the results:
List students = persons.stream()
    .filter(p -> p.getAge() > 18)
    .map(Student::new)
    .collect(Collectors.toCollection(ArrayList::new));

No comments:

Post a Comment