Skip to content

Commit 708d384

Browse files
[Term Entry] Java Queue: .peek()
* add: java queue .peek() method term entry * minor tweaks * Minor changes ---------
1 parent eb7a2e8 commit 708d384

File tree

1 file changed

+140
-0
lines changed
  • content/java/concepts/queue/terms/peek

1 file changed

+140
-0
lines changed
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
---
2+
Title: '.peek()'
3+
Description: 'Returns the head element of the queue without removing it, or null if the queue is empty.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Algorithms'
9+
- 'Collections'
10+
- 'Data Structures'
11+
- 'Methods'
12+
CatalogContent:
13+
- 'learn-java'
14+
- 'paths/computer-science'
15+
---
16+
17+
In Java, the **`.peek()`** method retrieves the head element of a queue without removing it from the queue. If the queue has no elements, it returns `null` instead of throwing an exception. This makes it a safe way to check what element is next in line without modifying the queue structure.
18+
19+
## Syntax
20+
21+
```pseudo
22+
queueName.peek()
23+
```
24+
25+
**Return value:**
26+
27+
Retrieves the head of the queue without removing it. Returns `null` if the queue is empty.
28+
29+
## Example 1: Basic Usage of `.peek()`
30+
31+
This example demonstrates how `.peek()` is used to inspect the next element without removing it from the queue:
32+
33+
```java
34+
import java.util.Queue;
35+
import java.util.LinkedList;
36+
37+
public class Main {
38+
public static void main(String[] args) {
39+
// Create a queue for customer service
40+
Queue<String> customerQueue = new LinkedList<>();
41+
42+
// Add customers to the queue
43+
customerQueue.offer("Alice");
44+
customerQueue.offer("Bob");
45+
customerQueue.offer("Charlie");
46+
47+
System.out.println("Queue: " + customerQueue);
48+
49+
// Peek at the next customer without removing them
50+
String nextCustomer = customerQueue.peek();
51+
System.out.println("Next customer to be served: " + nextCustomer);
52+
53+
// Queue remains unchanged after peek
54+
System.out.println("Queue after peek: " + customerQueue);
55+
System.out.println("Queue size: " + customerQueue.size());
56+
57+
// Serve the customer
58+
String servedCustomer = customerQueue.poll();
59+
System.out.println("Served customer: " + servedCustomer);
60+
System.out.println("Updated queue: " + customerQueue);
61+
}
62+
}
63+
```
64+
65+
The output of this code is:
66+
67+
```shell
68+
Queue: [Alice, Bob, Charlie]
69+
Next customer to be served: Alice
70+
Queue after peek: [Alice, Bob, Charlie]
71+
Queue size: 3
72+
Served customer: Alice
73+
Updated queue: [Bob, Charlie]
74+
```
75+
76+
This example shows how `.peek()` provides read-only access to the head element, keeping the queue unchanged until an actual removal operation is performed.
77+
78+
## Example 2: Handling Empty Queues with `.peek()`
79+
80+
This example shows how `.peek()` safely handles empty queues by returning `null` instead of throwing exceptions:
81+
82+
```java
83+
import java.util.Queue;
84+
import java.util.LinkedList;
85+
86+
public class EmptyQueueHandling {
87+
public static void main(String[] args) {
88+
Queue<String> messageQueue = new LinkedList<>();
89+
90+
// Peek at empty queue
91+
String result = messageQueue.peek();
92+
System.out.println("Peek on empty queue: " + result);
93+
System.out.println("Queue is empty: " + messageQueue.isEmpty());
94+
95+
// Add some messages
96+
messageQueue.offer("Welcome message");
97+
messageQueue.offer("Alert notification");
98+
99+
// Peek at non-empty queue
100+
String nextMessage = messageQueue.peek();
101+
System.out.println("Next message: " + nextMessage);
102+
103+
// Process all messages while checking what's next
104+
while (!messageQueue.isEmpty()) {
105+
String current = messageQueue.peek();
106+
System.out.println("About to process: " + current);
107+
108+
String processed = messageQueue.poll();
109+
System.out.println("Processed: " + processed);
110+
111+
// Check if there are more messages
112+
String upcoming = messageQueue.peek();
113+
if (upcoming != null) {
114+
System.out.println("Next up: " + upcoming);
115+
} else {
116+
System.out.println("No more messages in queue");
117+
}
118+
System.out.println("---");
119+
}
120+
}
121+
}
122+
```
123+
124+
The output of this code is:
125+
126+
```shell
127+
Peek on empty queue: null
128+
Queue is empty: true
129+
Next message: Welcome message
130+
About to process: Welcome message
131+
Processed: Welcome message
132+
Next up: Alert notification
133+
---
134+
About to process: Alert notification
135+
Processed: Alert notification
136+
No more messages in queue
137+
---
138+
```
139+
140+
This example demonstrates the safety of `.peek()` when dealing with potentially empty queues, making it ideal for defensive programming practices.

0 commit comments

Comments
 (0)