Peek, Limit, Sort

Learn about Peek, Limit, and Sort methods.

We'll cover the following

Peek

The Peek method in Java is used to fetch the first element in a stack. We can peek into a stream to do some action without interrupting the stream.

For example, we could print out elements to debug code:

Files.list(Paths.get("."))
     .map(Path::getFileName)
     .peek(System.out::println)
     .forEach(p -> doSomething(p));

We can use any action we want, but we should not try to modify elements. We should use map instead.

Let’s see an example of peek() below:

Get hands-on with 1200+ tech skills courses.