Junior — Middle
What is the difference between intermediate and terminal methods in programming?
sobes.tech AI
Answer from AI
In Java, Stream API methods are divided into intermediate and terminal.
Intermediate methods return a new Stream and allow building a chain of operations. They are lazy, meaning they are not executed immediately but only when a terminal method is called. Examples: filter(), map(), sorted().
Terminal methods trigger the execution of the entire chain of operations and return a result (not a Stream). After their invocation, the Stream is considered used and cannot be reused. Examples: collect(), forEach(), reduce().
Example:
List<String> names = List.of("Anna", "Bob", "Charlie");
List<String> filtered = names.stream() // create a Stream
.filter(name -> name.startsWith("A")) // intermediate method
.map(String::toUpperCase) // intermediate method
.collect(Collectors.toList()); // terminal method
System.out.println(filtered); // [ANNA]