﻿ How to Get the Position of a Element in a Queue - ITCodar

# How to Get the Position of a Element in a Queue

## How to get the position of a element in a Queue

As you already knew that `queue` is a collection that gives us `FIFO` by adding (to the last) and polling (from the head/first).

Which it also means there is no guarantee that you can use it to locate its `index/position` in the queue.

If you really need something like that, instead you can try `List` to achieve the same effect as follows using `add(E e)` and `remove(0)` and `indexOf(Object o)`:

``public static void main(String... args) {    List<Integer> list = new ArrayList<>();    int[] arr = new int[]{1,0,5,4,7,8,6};    for (int a : arr) {        list.add(a);    }    System.out.println("After adding: " + list);    System.out.println(list.indexOf(4));    System.out.print("Popping out now: ");    while(!list.isEmpty()) {        System.out.print(list.remove(0) + " ");    }}``

And the result will be:

``After adding: [1, 0, 5, 4, 7, 8, 6]3 // you can find the index easily;Popping out now: 1 0 5 4 7 8 6 // still FIFO;``

## How to get a particular element from Queue?

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;         }}``

## Getting index of an element in a std::queue by its value

If you want to get the index of an element you should probably consider using an `std::deque` container instead of a `std::queue` container adapter, as already suggested in this other answer.

If you still want to stick to to the `std::queue` container adapter for some other reason, you should know that it does provide access to the underlying container through the protected data member `c`.

You could derive from `std::queue` in order to access the underlying container and use the `std::find()` function template for finding an element in that container with such a value. Then, simply return the position of that element by using `std::distance()`.

``#include <algorithm>#include <queue>template<typename T>class Queue: std::queue<T> {public:   auto getPosition(const T& val) const {      auto it = std::find(this->c.begin(), this->c.end(), val);      return std::distance(this->c.begin(), it);   }// ...};``

If the element is not found, the index will correspond to the one returned by the `size()` member function.

If there are duplicates, this solution based on `std::find()` will return the position of the first one, i.e., the first element found with the requested value `val`.

## Get the index of an element inside queue c#

Maybe a `List` or an `Array` would be better for such actions but you could try this:

``queue.ToArray().ToList().IndexOf(email);``

## Queue return elements in Nth position

I will start by warning you that this is a lousy answer that does not actually solve your problem, because I can't figure out what your goal is. It does, however, explain the infinite loop you've encountered.

The infinite loop is the `while`, which waits for `Queue a` to be empty, which will never happen (unless `a` was already empty when the `while` loop started).

Each iteration through your `while` loop de-queues two items from `a`, and then en-queues the first item. Even if this is what you intended for most of the iterations (I honestly can't tell), it fails for what should have been the last one.

When `a` is down to just one element, your `while` loop starts repeating this useless behavior forever:

1. Remove the one and only element from `Queue a`.

2. Remove another element from the now-empty `a`... somehow.

3. Print God-knows-what, followed by a space.

4. Put that "one and only" element (the one that actually existed) right back onto `a`.

5. Test if `a` is empty, which --- surprise --- it is not.

6. Go to 1.

7. Heat-Death of the Universe.

Once `Queue a` gets caught in this trap, it will "always" contain that last element. The brief moments during which it is empty will occur only in the middle of the `while` block, and never during the iteration test at the top of that same block.

Other Weirdness

I came up with these questions while typing this answer. They are questions you should ask yourself:

• What is the goal of your program? (This will be required for almost any Stack Overflow questions you ask in the future. Its near-absence from this question is why you've received such an incomplete answer.)

• What happens when you call `leave` on an empty `Queue`? (Your `while` loop does this forever.) Why is that the obviously correct thing to do? What are the alternatives, and why are they obviously incorrect?

• What is `Queue temp` for? It never has more than one item in it, so why can't it be replaced with a local variable?

• Why do you print the items you throw away? Alternatively: Why do you throw away the items you print? Is printing them to the console something you wanted to do at all?

• What does any of this have to do with the "Nth position" in your title?

For future questions, I suggest you review the Help Center's "How do I ask a good question?" and the links at the bottom of that article, especially Eric Lippert's "How To Debug Small Programs". I suspect your code could benefit a lot from the latter's "Rubber Duck Debugging":

Explain to the duck using simple words why each line of each method in your program is obviously correct. At some point you will be unable to do so, either because you don't understand the method you wrote, or because it's wrong, or both. Concentrate your efforts on that method; that's probably where the bug is.

The duck would have caught many of these, I think.

## Check the current position in a Redis list of some list element

You can use a sorted set and a counter to more elegantly solve the problem.

### Push a job

1. Call `INCR counter` to get a counter.
2. Use the counter as score of the job, and call `ZADD jobs counter job-name`

### Pop a job

Call `BZPOPMIN jobs` to get the first unprocessed job.

### Get job position

Call `ZRANK jobs job-name` to get the rank of the job, e.g. the current position of the job.

## Deque get a value by its position

The Queue interface could not be used to traverse it's values or get a value by it's position, without removing elements from queue. Take a look at JavaDoc for it's methods.

But as long as it implements LinkedList in your case, you are able to cast your queue to List or even to LinkedList, if you need it's specific behaviour, and use it as you need it. For example, with simle List:

``List list = (LinkedList) queue;//print all contentfor (String temp : list) {  System.out.println(temp);}//get the second element in a listString value = list.get(1);``