Monday 18 October 2021

Java: remove oldest elements from the Queue

In this post, I am going to explain two implementations of Queue, which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.

 

What is a Queue?

Queue is a linear data structure, in which whatever comes first will go out first.

 

 


Insertion and deletion in queues take place from the opposite ends of the queue. As you see above image, insertion takes place at the rear end of the queue and the deletion takes place at the front of the queue.

 

How to remove oldest element from the queue, when the size is full?

We can do this using two collecitons.

a.   Guava EvictingQueue

b.   CircularFifoQueue of commons collections

 

Implementation 1: Using Guava EvictingQueue

EvictingQueue is a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.

 

You should specify the size of queue while defining it.

 

Example

EvictingQueue<Integer> queue = EvictingQueue.create(5);


Find the below working application.

 

EvictingQueueDemo.java

package com.sample.app.collections;

import com.google.common.collect.EvictingQueue;

public class EvictingQueueDemo {

	public static void main(String args[]) {
		// Set maximum size to 5.
		EvictingQueue<Integer> queue = EvictingQueue.create(5);

		queue.add(2);
		queue.add(3);
		queue.add(5);
		queue.add(7);
		queue.add(11);

		System.out.println("Queue -> " + queue);

		System.out.println("\nAdd one more element to the queue");

		queue.add(13);

		System.out.println("\nQueue -> " + queue);

	}

}


Output

Queue -> [2, 3, 5, 7, 11]

Add one more element to the queue

Queue -> [3, 5, 7, 11, 13]


Dependency used

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>31.0.1-jre</version>
</dependency>


Approach 2: Using CircularFifoQueue of apache commons collection.

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

 

Example

CircularFifoQueue<Integer> queue = new CircularFifoQueue(5);

 

Above snippet set the maximum size of queue to 5.

 

Find the below working application.

 

CircularFifoQueueDemo.java

 

package com.sample.app.collections;

import org.apache.commons.collections4.queue.CircularFifoQueue;

public class CircularFifoQueueDemo {

	public static void main(String args[]) {
		// Set maximum size to 5.
		CircularFifoQueue<Integer> queue = new CircularFifoQueue(5);

		queue.add(2);
		queue.add(3);
		queue.add(5);
		queue.add(7);
		queue.add(11);

		System.out.println("Queue -> " + queue);

		System.out.println("\nAdd one more element to the queue");

		queue.add(13);

		System.out.println("\nQueue -> " + queue);

	}

}

Output

Queue -> [2, 3, 5, 7, 11]

Add one more element to the queue

Queue -> [3, 5, 7, 11, 13]


You may like

No comments:

Post a Comment