Let’s first look how sequential streams work. First we create a sample source in form of a list of strings:

    Filter accepts a predicate to filter all elements of the stream. This operation is intermediate which enables us to call another stream operation (forEach) on the result. ForEach accepts a consumer to be executed for each element in the filtered stream. ForEach is a terminal operation. It’s void, so we cannot call another stream operation.

    1. stringCollection
    2. .stream()
    3. .filter((s) -> s.startsWith("a"))
    4. .forEach(System.out::println);
    5. // "aaa2", "aaa1"

    Sorted is an intermediate operation which returns a sorted view of the stream. The elements are sorted in natural order unless you pass a custom Comparator.

    1. System.out.println(stringCollection);

    The intermediate operation map converts each element into another object via the given function. The following example converts each string into an upper-cased string. But you can also use map to transform each object into another type. The generic type of the resulting stream depends on the generic type of the function you pass to map.

    Various matching operations can be used to check whether a certain predicate matches the stream. All of those operations are terminal and return a boolean result.

    1. boolean anyStartsWithA =
    2. stringCollection
    3. .stream()
    4. .anyMatch((s) -> s.startsWith("a"));
    5. System.out.println(anyStartsWithA); // true
    6. boolean allStartsWithA =
    7. stringCollection
    8. .stream()
    9. .allMatch((s) -> s.startsWith("a"));
    10. boolean noneStartsWithZ =
    11. stringCollection
    12. .stream()
    13. .noneMatch((s) -> s.startsWith("z"));
    14. System.out.println(noneStartsWithZ); // true

    Count

    This terminal operation performs a reduction on the elements of the stream with the given function. The result is an Optional holding the reduced value.

    1. Optional<String> reduced =
    2. stringCollection
    3. .stream()
    4. .sorted()
    5. .reduce((s1, s2) -> s1 + "#" + s2);