Reversing a Queue<Integer> and converting it into an int array

ZhaoGang :

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:

  1. the explict casting (List)queue;
  2. 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.

Elliott Frisch :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36473&siteId=1