Search code examples
javacollections

How to get a particular element from Queue?


Unlike ArrayList, there is no get(int index) method in Queue to retrieve the element at specified position.

Anybody please tell me how to achieve this in Queue?

Thanks.


Solution

  • You can remove elements from the Queue until you reach the needed one. You can re-add the removed elements at the end of the queue or put them in a different queue (and add the rest after you reached the needed element).

    You really shouldn't be using a Queue like that, though!

    public static <T> T get(Queue<T> queue, int index) {
        synchronized (queue) {
            if (queue == null) {
                return null;
            }
    
            int size = queue.size();
            if (index < 0 || size < index + 1) {
                return null;
            }
    
            T element = null;
            for (int i = 0; i < size; i++) {
                if (i == index) {
                    element = queue.remove();
                } else {
                    queue.add(queue.remove());
                }
            }
    
            return element;     
        }
    }