Showing posts with label queue. Show all posts
Showing posts with label queue. Show all posts

Sunday, 10 July 2022

Implement circular buffer using fixed length StringBuffer

Assume you have a fixed length string buffer, and implement a circular queue kind of functionality using it.

 

Example

String buffer with size 5 can hold 5 characters ABCDE, When I append new character ‘F’ to the existing string buffer, the resukting buffer should be BCDEF.

 

We can achieve this functionality using StringBuffer delete and append methods.

 

public StringBuffer delete(int start, int end)

Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.

 

public StringBuffer append(CharSequence s)

Appends the specified CharSequence to this sequence.

 

Example


 

Find the below working application.

 

CircularStringBuffer.java

package com.sample.app;

import java.util.StringJoiner;

public class CircularStringBuffer {

	private final int maxLength;
	private final StringBuffer stringBuffer;

	public CircularStringBuffer(int length) {
		if (length <= 0) {
			length = 10;
		}
		this.stringBuffer = new StringBuffer(length);

		this.maxLength = length;
	}

	void append(final String input) {
		final int bufferLength = stringBuffer.length();
		final int inputLength = input.length();

		if (bufferLength + inputLength > maxLength) {
			stringBuffer.delete(0, bufferLength + inputLength - maxLength);
		}
		stringBuffer.append(input, Math.max(0, inputLength - maxLength), inputLength);
	}

	@Override
	public String toString() {

		final StringJoiner joiner = new StringJoiner("->");

		for (char ch : stringBuffer.toString().toCharArray()) {
			joiner.add("" + ch);
		}

		return joiner.toString();
	}

}

App.java

package com.sample.app;

public class App {
	public static void main(String[] args) {
		CircularStringBuffer circularBuffer = new CircularStringBuffer(5);

		circularBuffer.append("A");
		System.out.println(circularBuffer);

		circularBuffer.append("B");
		System.out.println(circularBuffer);

		circularBuffer.append("C");
		System.out.println(circularBuffer);

		circularBuffer.append("D");
		System.out.println(circularBuffer);

		circularBuffer.append("E");
		System.out.println(circularBuffer);

		circularBuffer.append("F");
		System.out.println(circularBuffer);

		circularBuffer.append("G");
		System.out.println(circularBuffer);

		circularBuffer.append("H");
		System.out.println(circularBuffer);
	}
}

Output

A
A->B
A->B->C
A->B->C->D
A->B->C->D->E
B->C->D->E->F
C->D->E->F->G
D->E->F->G->H


Previous                                                 Next                                                 Home

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

Thursday, 26 December 2019

Get first element from a collection


Get first element from a list
Approach 1: Using index
int firstEle = list.get(0);

Approach 2: Using iterator
int firstEle = list.iterator().next();

Approach 3: Using stream
int firstEle = list.stream().findFirst().get();

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class App {

	public static void main(String args[]) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7);
		
		if(list.isEmpty()) {
			return;
		}
		
		int firstEle = list.get(0);
		firstEle = list.iterator().next();
		firstEle = list.stream().findFirst().get();
		
		
	}
}

Get first element from Queue
‘peek’ method is used to return first element in the queue.

Example
myQueue1.peek()


App.java
package com.sample.app;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class App {

	public static void main(String args[]) {

		Queue<Integer> myQueue1 = new ConcurrentLinkedQueue<>();

		/* Add Elements to myQueue */
		myQueue1.add(10);
		myQueue1.add(20);
		myQueue1.add(30);
		myQueue1.add(40);
		myQueue1.add(50);

		System.out.println("Head Element " + myQueue1.peek() + " Retrieved from the Queue ");

	}
}

Output
Head Element 10 Retrieved from the Queue


For unordered collections like Set, since order is not preserved you can’t get the first element.

You may like