Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Queue that ensure uniqueness of the elements?

I'm looking for a implementation of java.util.Queue or something in the Google collection who behave like a Queue, but also ensure that each element of the queue is unique. (all further insertion will have no effect)

It's that possible, or will I have to do it by hand?

For now I'm using a Queue, with a LinkedList implementation, and I check the uniqueness before insertion. ( I use a side Map for doing this, add / remove element from the side map before / after the queu ). I don't like it too much.

Any input is welcome. If it's not in the java.util package, then maybe it's a bad idea?

like image 259
Antoine Claval Avatar asked Feb 23 '10 15:02

Antoine Claval


People also ask

What are the 3 primary methods for a queue?

Basic queue operations: – Add (enqueue): Add an element to the back. – Remove (dequeue): Remove the front element.

What does queue element do?

The element() method in Java Queues is used to return the element at the front of the container and does not remove it.

What is the name of the method for adding an element to a queue?

#1) Enqueue: An operation to insert an element in the queue is Enqueue (function queueEnqueue in the program). For inserting an element at the rear end, we need to first check if the queue is full. If it is full, then we cannot insert the element.

How do you find the queue of an element?

When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue . Contains(T) Method is used to check whether an element is in the Queue .


2 Answers

How about a LinkedHashSet? Its iterator preserves insertion order, but because it's a Set, its elements are unique.

As its documentation says,

Note that insertion order is not affected if an element is re-inserted into the set.

In order to efficiently remove elements from the head of this "queue", go through its iterator:

Iterator<?> i = queue.iterator(); ... Object next = i.next(); i.remove(); 
like image 176
erickson Avatar answered Oct 02 '22 07:10

erickson


This doesn't exist as far as I know but would be fairly simple to implement using a LinkedList in conjunction with a Set:

/**  * Thread unsafe implementation of UniqueQueue.  */ public class UniqueQueue<T> implements Queue<T> {   private final Queue<T> queue = new LinkedList<T>();   private final Set<T> set = new HashSet<T>();    public boolean add(T t) {     // Only add element to queue if the set does not contain the specified element.     if (set.add(t)) {       queue.add(t);     }      return true; // Must always return true as per API def.   }    public T remove() throws NoSuchElementException {     T ret = queue.remove();     set.remove(ret);     return ret;   }    // TODO: Implement other Queue methods. } 
like image 39
Adamski Avatar answered Oct 02 '22 07:10

Adamski