The “peek()” method peeks at the memory, methods, class return values, or data stored in some data structures to extract the desired information. This information helps to perform several operations according to the requirements. Moreover, the application performance is also optimized by performing operations only when required.

For instance, if some function needs to be executed when a random data structure contains a specific value at the top position. Then, the peek method is used to check the value placed at the top of that specified data structure and then return that value. 

This article explains the working and usage of a “peek()” method in Java by covering the following concepts:

What is the “peek()” Method in Java?

The “peek()” method is utilized with data structures like Stack, Array, Queue, or LinkedLists to return their top position element. It works similarly to the “pop()” method which returns the top element of the attached data structure, but it also removes that element. But, the “peek()” method only retrieves that element without removing it from that data structure. As shown in below figure:

Syntax

The syntax for “peek()” method is mentioned below:

dataStructureName.peek()

The “dataStructureName” is the name of a created data structure whose top element is to be retrieved.

Parameter and Return Type

This method does not accept any parameters. It only returns the element residing at the top position of the attached data structure. 

Consider the below examples to explore the workings of a “peek()” method with multiple data structures.

How to Use the “peek()” Method With Stack?

The “peek()” method allows the users to select and return the element residing at the top of a Stack. This information about the Stack’s top element allows you to decide whether to perform the tasks on that element or not. It also helps in identifying whether the top element is what you are searching for or not. 

The implementation of “peek()” with the Stack is illustrated below:

import java.util.Stack;
public class Peeking {
public static void main(String[] args) {
  Stack<Object> demoStack = new Stack<Object>();
  demoStack.push(1725);
  demoStack.push(3470.231);
  demoStack.push(878456L);
  demoStack.push("Hello World");
  System.out.println("\nCreated Stack Elements -> " + demoStack);
  System.out.println("Element Residing at the Top in Stack => " + demoStack.peek());
}
}

The above code works like this:

  • First, create an “Object” type Stack named “demoStack” and store different types of data in it. Also, utilize the “push()” method to store the data in a Stack.
  • Next, print the “demoStack” content over the console. Also, apply the “peek()” method with “demoStack” to display the top element of a Stack.

The output shows that the top element is retrieved from the “peek()” method:

Note: In Stack, the element that is inserted at the end, holds the top position (which is “Hello World” in our case).

How to Use the “peek()” Method With Deque?

In Deque, the insertion of elements is performed according to the “First Come First Served” approach. So, the “peek()” element here returns the element residing at the top position which will be the element that is inserted first. The code is stated as:

import java.util.*;
public class Peeking {
//Defining the Main Method
public static void main(String[] args) {

//Declaring and Initializing an ArrayDeque
  Deque<Object> demoDeque = new ArrayDeque<Object>();

  demoDeque.offer(1725);
  demoDeque.offer(' ');
  demoDeque.offer(3470.231);
  demoDeque.offer(878456L);
  demoDeque.offer("Hello World");

//Prints the Top and All Elements of the Array Deque
  System.out.println("Element Residing at the Top in Array Deque =>  " + demoDeque.peek());
  System.out.println("\n Array Deque Elements ->  " + demoDeque);
}
}

The description of the above code is as follows:

  • First, create a Deque named “demoDeque” using the “ArrayDeque” class with the data type of “Object”. This data type allows you to insert any type of data in the created “ArrayDeque”.
  • Next, insert data with different or the same data type in the “demoDeque” using the “offer()” method. 
  • Now, apply the “peek()” method with the “demoDeque” to retrieve the top element of “ArrayDeque”.
  • Finally, display the returned element along with the entire “demoDeque” on a console.

The below output shows the retrieval of the top element “1725” that is inserted at first in the ArrayDeque:

How to Use the “peek()” Method With LinkedList?

Use the “peek()” method to select and return the top or head element from the LinkedList without removing it. The original LinkedList remains unchanged only the top element is retrieved, as shown below:

import java.util.*;
public class Peeking {
//Defining the main() Method
public static void main(String[] args) {

//Declaring and Initializing a LinkedList
  LinkedList <Object> demoList = new LinkedList<Object>();

  demoList.add(878456L);
  demoList.add(' ');
  demoList.add(3470.231);
  demoList.add(1725);
  demoList.add("Hello World");

//Prints the Top and All Elements of the Linked List
  System.out.println("Retrieved Top Element of a Linked List =>  " + demoList.peek());
  System.out.println("\n Linked List Elements -> " + demoList);
}
}

The explanation of the stated code is written below:

  • Initially, create a LinkedList “demoList” and insert random elements in it using the “add()” method.
  • After that, apply the “peek()” method on the “demoList” to select and retrieve the first element. 
  • Finally, print the entire “demoList” on a console window to confirm that the retrieved element is not removed from the LinkedList.

The below figure confirms the retrieval of a top position element from the LinkedList:

Bonus Tip: How to Use the Java 8 Stream “peek()” Method

The working of this “peek()” element is a lot different from the one we have discussed with different data structures. The “peek()” method of the Java 8 Stream API performs the specified actions on all Stream elements. This method is popular in Stream API to perform Logging, debugging or to apply a single action over all elements residing in the Stream. 

In the below code snippet, multiple filters are applied to the same data set to retrieve the desired data:

//Importing the Required Packagesimport java.util.*;
import java.util.stream.Collectors;

public class Peeking {
public static void main(String[] args) {
//Declaring and Initializing a Stack
  Stack <String> avengerStack = new Stack<String>();
  avengerStack.push("Iron Man");
  avengerStack.push("Ghost Rider");
  avengerStack.push("Captain America");
  avengerStack.push("Scarlet Witch");
  avengerStack.push("Scorpio");

  avengerStack.stream()
    .filter(s -> s.length() > 5)
    .peek(e -> System.out.println("\nFirst filter of Elements With Length greater than 5: " + e))
    .filter(s -> s.contains("r"))
    .peek(e -> System.out.println("\tSecond filter of String Containing the 'r' Character: " + e))
    .filter(s -> s.startsWith("S"))
    .peek(e -> System.out.println("\t\tThird filter of String Starting with 'S' Character: " + e))
    .filter(s -> s.endsWith("h"))
    .peek(e -> System.out.println("\t\t\tFourth filter of String Ending from 'h' Character: " + e))
    .collect(Collectors.toSet());
  }
}

The working of the above code snippet is as follows:

  • First, create a “String” type Stack named “avengerStack” in the “main()” method. Also, insert elements in this Stack by invoking the “push()” method.
  • Then, place the Stack “avengerStack” over the stream using the “stream()” method. 
  • Now, apply multiple “filter()” methods containing the Lambda expressions. These expressions filter out the “avengerStack” element according to specified criteria. This criterion is set by the combination of Lambda expression and Java methods like “contains()”, “startsWith()”, “length()”, etc.
  • Next, apply the “peek()” (next to each “filter()” method) to display the filtered element on the console. After that, pass the filtered element to the next “filter()” method, and so on.
  • Finally, store the results in a set using the “collect()” method and display them on the console as a result for each element.

The output confirms that elements that pass the filters are displayed on the console. The elements which are placed in “the green” container passed only “2” filters, the one in “red” passed all filters, and the one in “blue” passed three filters: 

That’s all about the usage of the “peek()” method in Java.

Conclusion

In Java, the “peek()” method allows the users to select and retrieve the top elements from the attached data structure like Stack, Queue, etc. This method is useful when the purpose is just to return the top element without performing any other operation like insertion or deletion. The Stream API also offers a “peek()” method that applies operations over the returned data from another Stream method like “filter()”.