I have a Queue<Integer>
declared as Queue<Integer> queue=new LinkedList();
, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code:
Collections.reverse((List)queue);
int[] res=queue.stream().mapToInt(Integer::intValue).toArray();
This code has two problems:
- the explict casting
(List)queue
; - I wonder if there is a one line solution.
So do we have any more elegant way to do this?
Clearification of the problem:
Whether the queue is reversed is not important. An int array of the reversed elements is what I need.
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());