Queues
A queue is a collection that allows you to access the elements in the order in which they were added instead of by ordinal position.
Journeyman · Java · Updated
A queue is a collection that allows you to access the elements in the order in which they were added instead of by ordinal position.
It is a First-In-First-Out (FIFO) type of list. Instead of accessing elements by their ordinal position, we access them by polling which element is next in line.
In Java, Queue is an interface. Here we create a LinkedList, which implements it, but we store it in a Queue variable so we can only use it like a queue.
New items are added to the queue by offering them to the queue. offer(item) adds the item to the end of the line.
Items are removed from the queue by polling the queue for the next item in line. poll() removes the first item in line.
Queue<String> players = new LinkedList<>();
players.offer("Emily");
players.offer("Lucas");
players.offer("Sophia");
players.offer("Mason");
while(!players.isEmpty())
{
String player = players.poll();
System.out.println(player);
}

Do it: serve the coffee line before closing
A coffee cart serves people in the order they joined the line: first in, first out. Ten minutes before closing, the barista knows how many more drinks there's time to make. Those people are served, in order, and everyone else stays in line for the cart that opens next door.
The method gets two values:
line: the people waiting, aQueue<String>, first in line at the front.drinksLeft: how many more drinks the barista can make, anint, such as2.
It returns a List<String>: the people served, in the order they were served. They leave the line; everyone else stays in it, in order.
For example:
Queue<String> line = new LinkedList<>();
line.offer("Emily");
line.offer("Lucas");
line.offer("Sophia");
line.offer("Mason");
List<String> served = serve(line, 2);
| Drink | Served | The line afterward |
|---|---|---|
| The start | Emily, Lucas, Sophia, Mason | |
| 1st | Emily | Lucas, Sophia, Mason |
| 2nd | Lucas | Sophia, Mason |
So served is ["Emily", "Lucas"], and line still holds Sophia, then Mason.
Your job: write the method serve(Queue<String> line, int drinksLeft).
- Take people from the front of the line, one per drink, up to
drinksLeftof them. - Return them in a list, in the order they were served.
- When the line runs out first, stop: everyone in it is served.
- When
drinksLeftis0, nobody is served: return an empty list and leave the line as it is.
Practiced live on the lesson page: write the Java right there and check it.