Java.Java8.What are terminal methods and what are not ?

✅ 1. Intermediate Methods (NOT terminal)

  • These build up the stream pipeline
  • Lazy – they don’t do anything until a terminal method is called
  • Always return a Stream (or IntStream, etc.)

🔹 Examples:

filter(), map(), flatMap(), sorted(), distinct(), limit(), skip(), peek()

These methods transform the stream and are usually chained.

✅ 2. Terminal Methods (Trigger execution)

  • These finalize the stream
  • Consume the pipeline and produce a result
  • Can return a value or cause a side effect
  • After a terminal method is called, the stream is closed and can’t be reused

🔹 Examples:

GroupMethods
Reductioncollect(), reduce(), count(), sum(), min(), max(), average()
IterationforEach(), forEachOrdered()
MatchinganyMatch(), allMatch(), noneMatch()
FindingfindFirst(), findAny()
ConversiontoArray()

🧠 Think of It Like This:

Stream OperationDoes it return a stream?Is it lazy?Is it terminal?
.map()✅ Yes✅ Yes❌ No
.filter()✅ Yes✅ Yes❌ No
.sorted()✅ Yes✅ Yes❌ No
.limit()✅ Yes✅ Yes❌ No
.forEach()❌ No (returns void)❌ No✅ Yes
.collect()❌ No (returns result)❌ No✅ Yes
.count()❌ No❌ No✅ Yes

“Terminal methods start the pipeline execution.”


🔹 Think of a stream pipeline like a water pipe:

  • Intermediate methods = assembling and configuring the pipe (filters, twists, splits)
  • Terminal method = turning on the faucet 💧 — only then the water (data) flows

✅ Why Terminal Methods Trigger Everything

  • Streams in Java are lazy — intermediate methods do nothing until a terminal method is called.
  • Terminal methods pull the data through all intermediate steps.

🔸 Real-World Analogy

Let’s say you’re building a factory line:

List<String> items = List.of("apple", "banana", "avocado");

items.stream()                 // define the conveyor belt
     .filter(s -> s.startsWith("a"))   // step 1: filter
     .map(String::toUpperCase);        // step 2: transform

Nothing happens yet! 😴

But once you call:

     .forEach(System.out::println);    // terminal: run the machine!

Now everything kicks in.

✅ Summary:

🔧 Intermediate Methods🚀 Terminal Methods
Just configure the streamExecute and produce results
Return a streamReturn a value / side effect
Lazy — do nothing aloneStart processing
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.