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

  • A+
Category:Languages

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.

 


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]); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: