Reversing a Queue<Integer> and converting it into an int array
No need to get fancy here.
static int[] toReversedArray(Queue<Integer> queue) {
int i = queue.size();
int[] array = new int[i];
for (int element : queue) {
array[--i] = element;
}
return array;
}
Not a one-liner, but easy to read and fast.
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int[]
and then use commons lang ArrayUtils.reverse(int[])
like
Queue<Integer> queue = new LinkedList<>();
// ...
int[] arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int[]
reverse method that allowed for a fluent interface (e.g. return the int[]
) then you could make it a one liner. Like,
public static int[] reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int[] arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
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]);
}