Java Example – Queue Usage
A queue is a special kind of linear list that only allows deletion operations at the front of the list and insertion operations at the rear of the list.
The LinkedList class implements the Queue interface, so we can use LinkedList as a Queue.
The following example demonstrates the usage of a Queue:
Main.java File
import
java
.
util
.
LinkedList
;
import
java
.
util
.
Queue
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
//
The add() and remove() methods throw an exception on failure (not recommended)
Queue
<
String
queue
=
new
LinkedList
<
String
(
)
;
//
Adding elements
queue
.
offer
(
"
a
"
)
;
queue
.
offer
(
"
b
"
)
;
queue
.
offer
(
"
c
"
)
;
queue
.
offer
(
"
d
"
)
;
queue
.
offer
(
"
e
"
)
;
for
(
String
q
:
queue
)
{
System
.
out
.
println
(
q
)
;
}
System
.
out
.
println
(
"
===
"
)
;
System
.
out
.
println
(
"
poll=
"
queue
.
poll
(
)
)
;
//
Returns the first element and removes it from the queue
for
(
String
q
:
queue
)
{
System
.
out
.
println
(
q
)
;
}
System
.
out
.
println
(
"
===
"
)
;
System
.
out
.
println
(
"
element=
"
queue
.
element
(
)
)
;
//
returns the first element
for
(
String
q
:
queue
)
{
System
.
out
.
println
(
q
)
;
}
System
.
out
.
println
(
"
===
"
)
;
System
.
out
.
println
(
"
peek=
"
queue
.
peek
(
)
)
;
//
returns the first element
for
(
String
q
:
queue
)
{
System
.
out
.
println
(
q
)
;
}
}
}
The output of the above code is:
a
b
c
d
e
===
poll=a
b
c
d
e
===
element=b
b
c
d
e
===
peek=b
b
c
d
e
Java Examples