Reputation: 148
Is there a simpel way to get the current position of a element in a Queue for example:
My current queue is [1,0,5,4,7,8,6]
i want to know the position of the 4 in this queue, in this exampel its 3, is there a way to achieve this with the java queue?
Upvotes: 0
Views: 8941
Reputation: 529
String value = "Value";
Queue<String> queueList= new LinkedList<>();
List listQueue= new ArrayList(queueList);
System.out.println("Index of : " + lista.indexOf("Value"));
Upvotes: 0
Reputation: 27
Queue may not be the best solution as it doesn't store an index. However, queue implements Iterable so you could iterate over the structure:
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(0);
queue.add(5);
queue.add(4);
queue.add(7);
queue.add(8);
queue.add(6);
int lookingFor = 0;
int counter = 0;
for (Integer number : queue) {
if (number == lookingFor) {
System.out.println(lookingFor + " is at position " + counter + " in the queue.");
break;
}
else counter++;
}
This will output the following:
0 is at position 1 in the queue.
Note this will find the first occurrence of 0 only.
Upvotes: 3
Reputation: 7838
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;
Upvotes: 1
Reputation: 188
The default interface of Queue does not have any methods for this. If you need this functionality I think you'll have to create your own implementation of the interface using an indexed collection under the hood.
Upvotes: 1
Reputation: 103
it supports FIFO, and size() you can't have the index of it. You have to count the remove actions on the pile.
Upvotes: 0