The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int[] res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int[] res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int[] res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object[] temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}