Sobes.tech
Middle

Tell about streams in Java: what groups do methods fall into and what is the difference?

sobes.tech AI

Answer from AI

In Java Stream API, methods can be conditionally divided into two groups:

  1. Intermediate methods — return a new stream, allowing to build a chain of operations without executing them immediately. Examples: filter(), map(), sorted(), distinct(), limit(), skip().

  2. Terminal methods — initiate stream processing and return a result or a side effect. After calling a terminal method, the stream is considered consumed and cannot be used further. Examples: collect(), forEach(), reduce(), count(), anyMatch(), allMatch().

The difference is that intermediate methods are lazy — they postpone execution, while terminal methods initiate data processing.

Example:

List<String> names = List.of("Anna", "Bob", "Charlie", "David");

long count = names.stream()
    .filter(name -> name.length() > 3)  // intermediate
    .map(String::toUpperCase)           // intermediate
    .count();                          // terminal

System.out.println(count); // Will output the number of names longer than 3
Tell about streams in Java: what groups do methods… - sobes.tech