Skip to main content

Explain the use of peek() in streams.

Entry Java
Quick Answer peek() is an intermediate operation that performs a side effect (like logging) for each element as it passes through, then passes the element unchanged to the next stage. Useful for debugging: stream.filter(x -> x > 0).peek(x -> log(x)).map(x -> x * 2). Don't use peek() to modify elements (it's for inspection only). Not guaranteed to run in all cases if terminal op short-circuits.

Answer

peek is an intermediate operation for debugging.
Lets you inspect elements without modifying them.
Not intended for business logic.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice