Skip to content

Commit 5f95019

Browse files
[Term Entry] Java Queue: contains() (#7511)
* [Term Entry] Java Queue: contains() * Update content/java/concepts/queue/terms/contains/contains.md * Update content/java/concepts/queue/terms/contains/contains.md * Update content/java/concepts/queue/terms/contains/contains.md * Update content/java/concepts/queue/terms/contains/contains.md * Update content/java/concepts/queue/terms/contains/contains.md * Format + lint ---------
1 parent fc8ea00 commit 5f95019

File tree

1 file changed

+233
-0
lines changed

1 file changed

+233
-0
lines changed
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
---
2+
Title: 'contains()'
3+
Description: 'Checks whether a specific element is present in a Java Queue and returns a boolean value indicating the result'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Boolean'
9+
- 'Collections'
10+
- 'Methods'
11+
- 'Queues'
12+
CatalogContent:
13+
- 'learn-java'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`contains()`** method in Java's [Queue](https://www.codecademy.com/resources/docs/java/queue) interface that checks whether a specific element is present in the queue. This method returns `true` if the queue contains the specified element, and `false` otherwise. The `contains()` method is inherited from the [Collection](https://www.codecademy.com/resources/docs/java/collection) interface and provides an efficient way to verify the presence of elements without modifying the queue structure.
18+
19+
## Syntax
20+
21+
```pseudo
22+
boolean contains(Object element)
23+
```
24+
25+
**Parameters:**
26+
27+
- `element`: The element whose presence in the queue is to be checked.
28+
29+
**Return value:**
30+
31+
The method returns a boolean value:
32+
33+
- `true` if the queue contains the specified element.
34+
- `false` if the element is not found in the queue.
35+
36+
## Example 1: Basic `contains()` Usage in Java
37+
38+
This example demonstrates the fundamental usage of the `contains()` method with a `LinkedList` queue implementation:
39+
40+
```java
41+
import java.util.LinkedList;
42+
import java.util.Queue;
43+
44+
public class QueueContainsExample {
45+
public static void main(String[] args) {
46+
// Create a queue using LinkedList
47+
Queue<String> queue = new LinkedList<>();
48+
49+
// Add elements to the queue
50+
queue.add("Apple");
51+
queue.add("Banana");
52+
queue.add("Cherry");
53+
54+
// Check if queue contains specific elements
55+
boolean hasApple = queue.contains("Apple");
56+
boolean hasGrape = queue.contains("Grape");
57+
58+
System.out.println("Queue contains Apple: " + hasApple);
59+
System.out.println("Queue contains Grape: " + hasGrape);
60+
}
61+
}
62+
```
63+
64+
The output of this code is:
65+
66+
```shell
67+
Queue contains Apple: true
68+
Queue contains Grape: false
69+
```
70+
71+
This example creates a queue with fruit names and demonstrates how `contains()` returns `true` for existing elements and `false` for non-existing elements.
72+
73+
## Example 2: Customer Order Processing with `contains()`
74+
75+
This example shows how the `contains()` method can be used in a real-world customer order processing system to check if specific orders are pending:
76+
77+
```java
78+
import java.util.LinkedList;
79+
import java.util.Queue;
80+
81+
public class OrderProcessor {
82+
public static void main(String[] args) {
83+
// Create a queue to store pending order IDs
84+
Queue<Integer> pendingOrders = new LinkedList<>();
85+
86+
// Add some order IDs to the queue
87+
pendingOrders.add(1001);
88+
pendingOrders.add(1002);
89+
pendingOrders.add(1003);
90+
pendingOrders.add(1004);
91+
92+
// Check if specific orders are in the pending queue
93+
int customerOrder = 1002;
94+
if (pendingOrders.contains(customerOrder)) {
95+
System.out.println("Order " + customerOrder + " is currently pending");
96+
System.out.println("Estimated position in queue: " + getOrderPosition(pendingOrders, customerOrder));
97+
} else {
98+
System.out.println("Order " + customerOrder + " is not in the pending queue");
99+
}
100+
101+
// Check another order
102+
int anotherOrder = 1005;
103+
if (pendingOrders.contains(anotherOrder)) {
104+
System.out.println("Order " + anotherOrder + " is currently pending");
105+
} else {
106+
System.out.println("Order " + anotherOrder + " has been processed or doesn't exist");
107+
}
108+
}
109+
110+
// Helper method to find position of order in queue
111+
private static int getOrderPosition(Queue<Integer> queue, int orderId) {
112+
int position = 1;
113+
for (Integer order : queue) {
114+
if (order.equals(orderId)) {
115+
return position;
116+
}
117+
position++;
118+
}
119+
return -1; // Not found
120+
}
121+
}
122+
```
123+
124+
The output of this code is:
125+
126+
```shell
127+
Order 1002 is currently pending
128+
Estimated position in queue: 2
129+
Order 1005 has been processed or doesn't exist
130+
```
131+
132+
This example demonstrates how businesses can use the `contains()` method to quickly verify order status and provide customers with accurate information about their pending orders.
133+
134+
## Example 3: Task Management System with `contains()`
135+
136+
This example illustrates using the `contains()` method in a task management system where different priority tasks are queued for execution:
137+
138+
```java
139+
import java.util.PriorityQueue;
140+
import java.util.Queue;
141+
142+
class Task implements Comparable<Task> {
143+
private String name;
144+
private int priority;
145+
146+
public Task(String name, int priority) {
147+
this.name = name;
148+
this.priority = priority;
149+
}
150+
151+
@Override
152+
public int compareTo(Task other) {
153+
return Integer.compare(this.priority, other.priority); // Lower number = higher priority
154+
}
155+
156+
@Override
157+
public boolean equals(Object obj) {
158+
if (this == obj) return true;
159+
if (obj == null || getClass() != obj.getClass()) return false;
160+
Task task = (Task) obj;
161+
return name.equals(task.name);
162+
}
163+
164+
@Override
165+
public String toString() {
166+
return name + " (Priority: " + priority + ")";
167+
}
168+
}
169+
170+
public class TaskManager {
171+
public static void main(String[] args) {
172+
// Create a priority queue for task management
173+
Queue<Task> taskQueue = new PriorityQueue<>();
174+
175+
// Add tasks with different priorities
176+
taskQueue.add(new Task("Database Backup", 1));
177+
taskQueue.add(new Task("Send Email Report", 3));
178+
taskQueue.add(new Task("Update Security Patches", 1));
179+
taskQueue.add(new Task("Clean Temp Files", 5));
180+
181+
// Check if specific tasks are scheduled
182+
Task searchTask1 = new Task("Database Backup", 1);
183+
Task searchTask2 = new Task("Generate Analytics", 2);
184+
185+
if (taskQueue.contains(searchTask1)) {
186+
System.out.println("Database Backup is scheduled for execution");
187+
}
188+
189+
if (taskQueue.contains(searchTask2)) {
190+
System.out.println("Generate Analytics is scheduled for execution");
191+
} else {
192+
System.out.println("Generate Analytics is not in the task queue");
193+
}
194+
195+
// Display current queue status
196+
System.out.println("\nCurrent tasks in queue:");
197+
for (Task task : taskQueue) {
198+
System.out.println("- " + task);
199+
}
200+
}
201+
}
202+
```
203+
204+
The output of this code is:
205+
206+
```shell
207+
Database Backup is scheduled for execution
208+
Generate Analytics is not in the task queue
209+
210+
Current tasks in queue:
211+
- Database Backup (Priority: 1)
212+
- Update Security Patches (Priority: 1)
213+
- Send Email Report (Priority: 3)
214+
- Clean Temp Files (Priority: 5)
215+
```
216+
217+
> **Note:** `PriorityQueue` iteration does not guarantee elements will appear in priority order - the displayed task sequence may vary between program runs due to internal heap storage organization.
218+
219+
This example shows how the `contains()` method can be used in system administration scenarios to verify whether critical tasks are queued for execution, helping administrators track and manage automated processes.
220+
221+
## Frequently Asked Questions
222+
223+
### 1. What is the `contains()` method in Java?
224+
225+
The `contains()` method for queues works with any object type, including strings. When used with String elements in a queue, it checks if a specific string value exists in the queue using the `equals()` method for comparison.
226+
227+
### 2. What is `contains()` in a priority queue in Java?
228+
229+
In a `PriorityQueue`, the `contains()` method searches through the internal heap structure to find the specified element. It returns `true` if the element exists, regardless of its position in the priority ordering. The time complexity is `O(n)` since it may need to check multiple elements.
230+
231+
### 3. Is Java priority queue max or min?
232+
233+
By default, Java's `PriorityQueue` is a min-heap, meaning the smallest element (according to natural ordering or provided Comparator) has the highest priority and is removed first. To create a max-heap, you need to provide a reverse Comparator or implement Comparable in reverse order.

0 commit comments

Comments
 (0)