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:
(List)queue
;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.
Reverse an array of characters without creating a new array using java. If you want to reverse int array, you have to change public static void reverseArray(String[] array) as public static void reverseArray(int[] array) and String temp as int temp . Save this answer.
Reversing a Queue 1 enqueue (x) : Add an item x to rear of queue. 2 dequeue () : Remove an item from front of queue. 3 empty () : Checks if a queue is empty or not.
(Topmost element of the stack is the last element of the queue) Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue) Time Complexity: O (n).
Sometimes programmers need to process arrays starting with the last element, in that case, it is always efficient to reverse the array so that the first element is placed at the last position in the array, and the second element is placed at the second last position in the array and so on until the last element is at the first index.
Not quite a one liner, but you could first convert to an int [] and then use commons lang ArrayUtils.reverse (int []) like 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,
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With