Java how to break stream chain

Java how to break stream chain

In Java, you can break a stream chain by using the collect() method or any terminal operation that consumes the elements of the stream. Stream operations are divided into two categories: intermediate operations and terminal operations.

  1. Intermediate Operations: These operations transform a stream into another stream, and they are usually chained together to create a sequence of transformations. Examples include filter(), map(), flatMap(), and distinct(). Intermediate operations do not trigger the execution of the stream pipeline; they are lazy.

  2. Terminal Operations: These operations consume the elements of the stream and produce a result or a side effect. Examples include forEach(), collect(), reduce(), and count(). Terminal operations are eager, meaning they trigger the execution of the stream pipeline.

To break the stream chain and force the execution of the stream pipeline, you can use any terminal operation. Here's an example:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamChainBreak {
    public static void main(String[] args) {
        List<String> fruits = Stream.of("apple", "banana", "cherry", "date")
                .filter(fruit -> fruit.length() > 5)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println(fruits);
    }
}

In this example, the stream operations are chained together with filter() and map(). The stream pipeline is executed when collect(Collectors.toList()) is called. This terminal operation collects the filtered and mapped elements into a list and breaks the stream chain.

You can also use other terminal operations like forEach(), reduce(), count(), or any other operation that consumes the elements of the stream to break the chain and trigger the execution of the intermediate operations.


More Tags

intellij-lombok-plugin blazor-server-side ssms concurrent-collections data-fitting git-rewrite-history list-comprehension image-uploading full-text-indexing azure-devops

More Java Questions

More Transportation Calculators

More Genetics Calculators

More Livestock Calculators

More Animal pregnancy Calculators