What is the peek method in Java Stream API and how to use it?

The peek method in Java’s Stream API is an intermediary operation. This method provides a way to inspect the elements in the stream as they’re being processed by other stream operations. However, it’s important to note that peek should only be used for debugging purposes, as it can be quite disruptive to the stream’s data flow, particularly when it’s used in parallel streams.

The key point of the peek operation is that it’s not a terminal operation (i.e., it doesn’t trigger data processing), instead, it integrates nicely within the operation chain, allowing insights to be gained during the processing phase.

Here’s a simple way of using it with Java:

package org.kodejava.util;

import java.util.stream.Stream;

public class PeekMethodStream {
    public static void main(String[] args) {
        Stream.of(1, 2, 3, 4, 5)
                .peek(i -> System.out.println("Number: " + i))
                .map(i -> i * i)
                .forEach(i -> System.out.println("Squared: " + i));


Number: 1
Squared: 1
Number: 2
Squared: 4
Number: 3
Squared: 9
Number: 4
Squared: 16
Number: 5
Squared: 25

In this code snippet:

  • We create a stream with Stream.of(1, 2, 3, 4, 5).
  • Then we use peek to print each element in its current state: “Number: 1”, “Number: 2”, etc.
  • After that, we use map to square each element.
  • Finally, we use forEach to print the squared numbers: “Squared: 1”, “Squared: 4”, etc.

Remember, use peek carefully and preferably only for debugging purposes.

How do I create a Last-In-First-Out Deque?

This example show you how to create a LIFO (Last In First Out) Deque. We call the Deque.peekLast() method to get the last element from the Deque, poll the last element and repeat until all the elements read.

package org.kodejava.util;

import java.util.Deque;
import java.util.LinkedList;

public class DequeLifoDemo {

    public static void main(String[] args) {
        // Create an instance of a Deque, here we use the LinkedList
        // class which implements the Deque interface.
        Deque<String> deque = new LinkedList<>();

        StringBuilder in = new StringBuilder("Items IN in order : ");

        // Returns an iterator over the elements in this deque in
        // proper sequence
        for (String s : deque) {

        in.deleteCharAt(in.length() - 1);

        StringBuilder out = new StringBuilder("Items OUT in order: ");
        for (int i = 0; i < deque.size(); ) {

            // Retrieves and removes the last element of this deque,
            // or returns null if this deque is empty.

        out.deleteCharAt(out.length() - 1);

The output of our code snippet is:

Items IN in order : one,two,three,four
Items OUT in order: four,three,two,one