Reversing a Queue and converting it into an int array












11















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.










share|improve this question





























    11















    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.










    share|improve this question



























      11












      11








      11


      3






      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.










      share|improve this question
















      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.







      java collections queue






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 4 at 9:33









      Moira

      5,52221937




      5,52221937










      asked Jan 4 at 1:18









      ZhaoGangZhaoGang

      1,9011116




      1,9011116
























          9 Answers
          9






          active

          oldest

          votes


















          5














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





          share|improve this answer
























          • but this wouldn't reverse the queue.

            – nullpointer
            Jan 4 at 1:39








          • 2





            @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

            – Elliott Frisch
            Jan 4 at 1:42



















          7














          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.






          share|improve this answer































            6














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





            share|improve this answer


























            • You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

              – Marcono1234
              Jan 4 at 2:39






            • 2





              If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

              – Slaw
              Jan 4 at 2:39













            • @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

              – nullpointer
              Jan 4 at 3:43













            • @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

              – João Rebelo
              Jan 4 at 10:43



















            3














            In Java8 version you can use Stream API to help you.



            The skeleton of code like this:



            int reversedQueue = queue.stream()
            .collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
            .stream().mapToInt(Integer::intValue).toArray();





            share|improve this answer
























            • It looks like your combiner ((a,b)->a) is missing b in the result

              – Marcono1234
              Jan 4 at 2:52











            • @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

              – TongChen
              Jan 4 at 3:24











            • it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

              – Marcono1234
              Jan 5 at 0:00



















            2














            You can use the LazyIterate utility from Eclipse Collections as follows.



            int res = LazyIterate.adapt(queue)
            .collectInt(i -> i)
            .toList()
            .asReversed()
            .toArray();


            You can also use the Collectors2 class with a Java Stream.



            int ints = queue.stream()
            .collect(Collectors2.collectInt(i -> i, IntLists.mutable::empty))
            .asReversed()
            .toArray();


            You can stream the int values directly into a MutableIntList, reverse it, and then convert it to an int array.



            int ints =
            IntLists.mutable.ofAll(queue.stream().mapToInt(i -> i)).asReversed().toArray();


            Finally, you can stream the int values directly into a MutableIntStack and convert it to an int array.



            int ints =
            IntStacks.mutable.ofAll(queue.stream().mapToInt(i -> i)).toArray();


            Note: I am a committer for Eclipse Collections.






            share|improve this answer

































              2














              Finally, I figure out this one line solution.



              Integer intArray = queue.stream()
              .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll)
              .toArray(new Integer[queue.size()]);


              the int version should like



              int intArray = queue.stream()
              .collect(LinkedList<Integer>::new, LinkedList::addFirst, LinkedList::addAll)
              .stream()
              .mapToInt(Integer::intValue)
              .toArray();





              share|improve this answer


























              • Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                – Keijack
                Jan 4 at 8:05



















              1














              This is one line, but it may not be very efficient:



              int res = queue.stream()
              .collect(LinkedList<Integer>::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
              .stream()
              .mapToInt(Integer::intValue)
              .toArray();


              If you want to be efficient and readable, you should continue using what you have now.






              share|improve this answer


























              • This does not reverse the queue (or its values)

                – Marcono1234
                Jan 4 at 2:50



















              0














              Here is a different solution using Stream and Collections.reverse() in one line of code:



              Integer reversedArray = queue.stream()
              .collect(Collectors.collectingAndThen(Collectors.toList(),
              list -> {
              Collections.reverse(list);
              return list.toArray(new Integer[0]);
              }
              ));


              OR



              int reversedArray = queue.stream()
              .collect(Collectors.collectingAndThen(Collectors.toList(),
              list -> {
              Collections.reverse(list);
              return list.stream()
              .mapToInt(Integer::intValue)
              .toArray();
              }
              ));





              share|improve this answer

































                0














                Here's a way that creates a reversed array without reversing the queue:



                int i = { queue.size() };
                int array = new int[i[0]];
                queue.forEach(n -> array[--i[0]] = n);


                The above code is quite hacky due to the impossibility to modify local variables from within lambda expressions. So here i needs to be a one-element array, to overcome this restriction.



                Note: bear in mind that I've come to this solution just for fun :)






                share|improve this answer

























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031994%2freversing-a-queueinteger-and-converting-it-into-an-int-array%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  9 Answers
                  9






                  active

                  oldest

                  votes








                  9 Answers
                  9






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  5














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





                  share|improve this answer
























                  • but this wouldn't reverse the queue.

                    – nullpointer
                    Jan 4 at 1:39








                  • 2





                    @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                    – Elliott Frisch
                    Jan 4 at 1:42
















                  5














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





                  share|improve this answer
























                  • but this wouldn't reverse the queue.

                    – nullpointer
                    Jan 4 at 1:39








                  • 2





                    @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                    – Elliott Frisch
                    Jan 4 at 1:42














                  5












                  5








                  5







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





                  share|improve this answer













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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 4 at 1:35









                  Elliott FrischElliott Frisch

                  153k1389178




                  153k1389178













                  • but this wouldn't reverse the queue.

                    – nullpointer
                    Jan 4 at 1:39








                  • 2





                    @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                    – Elliott Frisch
                    Jan 4 at 1:42



















                  • but this wouldn't reverse the queue.

                    – nullpointer
                    Jan 4 at 1:39








                  • 2





                    @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                    – Elliott Frisch
                    Jan 4 at 1:42

















                  but this wouldn't reverse the queue.

                  – nullpointer
                  Jan 4 at 1:39







                  but this wouldn't reverse the queue.

                  – nullpointer
                  Jan 4 at 1:39






                  2




                  2





                  @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                  – Elliott Frisch
                  Jan 4 at 1:42





                  @nullpointer True. But, if the goal is a reversed int then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int is returned to the caller.

                  – Elliott Frisch
                  Jan 4 at 1:42













                  7














                  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.






                  share|improve this answer




























                    7














                    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.






                    share|improve this answer


























                      7












                      7








                      7







                      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.






                      share|improve this answer













                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 4 at 7:02









                      xehpukxehpuk

                      4,4322335




                      4,4322335























                          6














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





                          share|improve this answer


























                          • You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                            – Marcono1234
                            Jan 4 at 2:39






                          • 2





                            If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                            – Slaw
                            Jan 4 at 2:39













                          • @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                            – nullpointer
                            Jan 4 at 3:43













                          • @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                            – João Rebelo
                            Jan 4 at 10:43
















                          6














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





                          share|improve this answer


























                          • You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                            – Marcono1234
                            Jan 4 at 2:39






                          • 2





                            If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                            – Slaw
                            Jan 4 at 2:39













                          • @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                            – nullpointer
                            Jan 4 at 3:43













                          • @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                            – João Rebelo
                            Jan 4 at 10:43














                          6












                          6








                          6







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





                          share|improve this answer















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






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jan 4 at 8:31

























                          answered Jan 4 at 1:31









                          nullpointernullpointer

                          46k1198188




                          46k1198188













                          • You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                            – Marcono1234
                            Jan 4 at 2:39






                          • 2





                            If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                            – Slaw
                            Jan 4 at 2:39













                          • @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                            – nullpointer
                            Jan 4 at 3:43













                          • @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                            – João Rebelo
                            Jan 4 at 10:43



















                          • You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                            – Marcono1234
                            Jan 4 at 2:39






                          • 2





                            If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                            – Slaw
                            Jan 4 at 2:39













                          • @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                            – nullpointer
                            Jan 4 at 3:43













                          • @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                            – João Rebelo
                            Jan 4 at 10:43

















                          You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                          – Marcono1234
                          Jan 4 at 2:39





                          You should probably not be using the Stack class since it extends Vector and is therefore synchronized, which is not needed here and only decreases performance.

                          – Marcono1234
                          Jan 4 at 2:39




                          2




                          2





                          If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                          – Slaw
                          Jan 4 at 2:39







                          If using a Deque it might be more efficient to use Deque.descendingIterator() combined with Spliterators and StreamSupport, assuming only the reversed array is needed and not the reversed Deque. The code will be more verbose, however.

                          – Slaw
                          Jan 4 at 2:39















                          @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                          – nullpointer
                          Jan 4 at 3:43







                          @Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.

                          – nullpointer
                          Jan 4 at 3:43















                          @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                          – João Rebelo
                          Jan 4 at 10:43





                          @Marcono1234 actualy, the JVM does away with the synchronized blocks within the Vector class is its most recent versions when it detects they're are not shared and their aquisition cost is negligible :) but yeah, on principle you shouldn't do that as Vector is not recommended to be used anymore.

                          – João Rebelo
                          Jan 4 at 10:43











                          3














                          In Java8 version you can use Stream API to help you.



                          The skeleton of code like this:



                          int reversedQueue = queue.stream()
                          .collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
                          .stream().mapToInt(Integer::intValue).toArray();





                          share|improve this answer
























                          • It looks like your combiner ((a,b)->a) is missing b in the result

                            – Marcono1234
                            Jan 4 at 2:52











                          • @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                            – TongChen
                            Jan 4 at 3:24











                          • it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                            – Marcono1234
                            Jan 5 at 0:00
















                          3














                          In Java8 version you can use Stream API to help you.



                          The skeleton of code like this:



                          int reversedQueue = queue.stream()
                          .collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
                          .stream().mapToInt(Integer::intValue).toArray();





                          share|improve this answer
























                          • It looks like your combiner ((a,b)->a) is missing b in the result

                            – Marcono1234
                            Jan 4 at 2:52











                          • @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                            – TongChen
                            Jan 4 at 3:24











                          • it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                            – Marcono1234
                            Jan 5 at 0:00














                          3












                          3








                          3







                          In Java8 version you can use Stream API to help you.



                          The skeleton of code like this:



                          int reversedQueue = queue.stream()
                          .collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
                          .stream().mapToInt(Integer::intValue).toArray();





                          share|improve this answer













                          In Java8 version you can use Stream API to help you.



                          The skeleton of code like this:



                          int reversedQueue = queue.stream()
                          .collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
                          .stream().mapToInt(Integer::intValue).toArray();






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 4 at 1:59









                          TongChenTongChen

                          27529




                          27529













                          • It looks like your combiner ((a,b)->a) is missing b in the result

                            – Marcono1234
                            Jan 4 at 2:52











                          • @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                            – TongChen
                            Jan 4 at 3:24











                          • it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                            – Marcono1234
                            Jan 5 at 0:00



















                          • It looks like your combiner ((a,b)->a) is missing b in the result

                            – Marcono1234
                            Jan 4 at 2:52











                          • @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                            – TongChen
                            Jan 4 at 3:24











                          • it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                            – Marcono1234
                            Jan 5 at 0:00

















                          It looks like your combiner ((a,b)->a) is missing b in the result

                          – Marcono1234
                          Jan 4 at 2:52





                          It looks like your combiner ((a,b)->a) is missing b in the result

                          – Marcono1234
                          Jan 4 at 2:52













                          @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                          – TongChen
                          Jan 4 at 3:24





                          @Marcono1234 There is no problem.The third parameter of Collector.of method is one BinaryOperator it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.

                          – TongChen
                          Jan 4 at 3:24













                          it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                          – Marcono1234
                          Jan 5 at 0:00





                          it does not matter in this case probably since (if I understand it correctly) the combiner is only used for parallel streams. However, you should probably comment that the implementation is not correct, to prevent bugs in the future in case someone uses this code for a parallel stream. It should probably be (a, b) -> {b.addAll(a); return b;}.

                          – Marcono1234
                          Jan 5 at 0:00











                          2














                          You can use the LazyIterate utility from Eclipse Collections as follows.



                          int res = LazyIterate.adapt(queue)
                          .collectInt(i -> i)
                          .toList()
                          .asReversed()
                          .toArray();


                          You can also use the Collectors2 class with a Java Stream.



                          int ints = queue.stream()
                          .collect(Collectors2.collectInt(i -> i, IntLists.mutable::empty))
                          .asReversed()
                          .toArray();


                          You can stream the int values directly into a MutableIntList, reverse it, and then convert it to an int array.



                          int ints =
                          IntLists.mutable.ofAll(queue.stream().mapToInt(i -> i)).asReversed().toArray();


                          Finally, you can stream the int values directly into a MutableIntStack and convert it to an int array.



                          int ints =
                          IntStacks.mutable.ofAll(queue.stream().mapToInt(i -> i)).toArray();


                          Note: I am a committer for Eclipse Collections.






                          share|improve this answer






























                            2














                            You can use the LazyIterate utility from Eclipse Collections as follows.



                            int res = LazyIterate.adapt(queue)
                            .collectInt(i -> i)
                            .toList()
                            .asReversed()
                            .toArray();


                            You can also use the Collectors2 class with a Java Stream.



                            int ints = queue.stream()
                            .collect(Collectors2.collectInt(i -> i, IntLists.mutable::empty))
                            .asReversed()
                            .toArray();


                            You can stream the int values directly into a MutableIntList, reverse it, and then convert it to an int array.



                            int ints =
                            IntLists.mutable.ofAll(queue.stream().mapToInt(i -> i)).asReversed().toArray();


                            Finally, you can stream the int values directly into a MutableIntStack and convert it to an int array.



                            int ints =
                            IntStacks.mutable.ofAll(queue.stream().mapToInt(i -> i)).toArray();


                            Note: I am a committer for Eclipse Collections.






                            share|improve this answer




























                              2












                              2








                              2







                              You can use the LazyIterate utility from Eclipse Collections as follows.



                              int res = LazyIterate.adapt(queue)
                              .collectInt(i -> i)
                              .toList()
                              .asReversed()
                              .toArray();


                              You can also use the Collectors2 class with a Java Stream.



                              int ints = queue.stream()
                              .collect(Collectors2.collectInt(i -> i, IntLists.mutable::empty))
                              .asReversed()
                              .toArray();


                              You can stream the int values directly into a MutableIntList, reverse it, and then convert it to an int array.



                              int ints =
                              IntLists.mutable.ofAll(queue.stream().mapToInt(i -> i)).asReversed().toArray();


                              Finally, you can stream the int values directly into a MutableIntStack and convert it to an int array.



                              int ints =
                              IntStacks.mutable.ofAll(queue.stream().mapToInt(i -> i)).toArray();


                              Note: I am a committer for Eclipse Collections.






                              share|improve this answer















                              You can use the LazyIterate utility from Eclipse Collections as follows.



                              int res = LazyIterate.adapt(queue)
                              .collectInt(i -> i)
                              .toList()
                              .asReversed()
                              .toArray();


                              You can also use the Collectors2 class with a Java Stream.



                              int ints = queue.stream()
                              .collect(Collectors2.collectInt(i -> i, IntLists.mutable::empty))
                              .asReversed()
                              .toArray();


                              You can stream the int values directly into a MutableIntList, reverse it, and then convert it to an int array.



                              int ints =
                              IntLists.mutable.ofAll(queue.stream().mapToInt(i -> i)).asReversed().toArray();


                              Finally, you can stream the int values directly into a MutableIntStack and convert it to an int array.



                              int ints =
                              IntStacks.mutable.ofAll(queue.stream().mapToInt(i -> i)).toArray();


                              Note: I am a committer for Eclipse Collections.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 4 at 6:51

























                              answered Jan 4 at 3:36









                              Donald RaabDonald Raab

                              4,22112029




                              4,22112029























                                  2














                                  Finally, I figure out this one line solution.



                                  Integer intArray = queue.stream()
                                  .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll)
                                  .toArray(new Integer[queue.size()]);


                                  the int version should like



                                  int intArray = queue.stream()
                                  .collect(LinkedList<Integer>::new, LinkedList::addFirst, LinkedList::addAll)
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();





                                  share|improve this answer


























                                  • Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                    – Keijack
                                    Jan 4 at 8:05
















                                  2














                                  Finally, I figure out this one line solution.



                                  Integer intArray = queue.stream()
                                  .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll)
                                  .toArray(new Integer[queue.size()]);


                                  the int version should like



                                  int intArray = queue.stream()
                                  .collect(LinkedList<Integer>::new, LinkedList::addFirst, LinkedList::addAll)
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();





                                  share|improve this answer


























                                  • Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                    – Keijack
                                    Jan 4 at 8:05














                                  2












                                  2








                                  2







                                  Finally, I figure out this one line solution.



                                  Integer intArray = queue.stream()
                                  .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll)
                                  .toArray(new Integer[queue.size()]);


                                  the int version should like



                                  int intArray = queue.stream()
                                  .collect(LinkedList<Integer>::new, LinkedList::addFirst, LinkedList::addAll)
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();





                                  share|improve this answer















                                  Finally, I figure out this one line solution.



                                  Integer intArray = queue.stream()
                                  .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll)
                                  .toArray(new Integer[queue.size()]);


                                  the int version should like



                                  int intArray = queue.stream()
                                  .collect(LinkedList<Integer>::new, LinkedList::addFirst, LinkedList::addAll)
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 4 at 8:03

























                                  answered Jan 4 at 1:42









                                  KeijackKeijack

                                  1666




                                  1666













                                  • Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                    – Keijack
                                    Jan 4 at 8:05



















                                  • Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                    – Keijack
                                    Jan 4 at 8:05

















                                  Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                  – Keijack
                                  Jan 4 at 8:05





                                  Thanks @Hulk, add the int version, but I think I like the Integer version, simpler.

                                  – Keijack
                                  Jan 4 at 8:05











                                  1














                                  This is one line, but it may not be very efficient:



                                  int res = queue.stream()
                                  .collect(LinkedList<Integer>::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();


                                  If you want to be efficient and readable, you should continue using what you have now.






                                  share|improve this answer


























                                  • This does not reverse the queue (or its values)

                                    – Marcono1234
                                    Jan 4 at 2:50
















                                  1














                                  This is one line, but it may not be very efficient:



                                  int res = queue.stream()
                                  .collect(LinkedList<Integer>::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();


                                  If you want to be efficient and readable, you should continue using what you have now.






                                  share|improve this answer


























                                  • This does not reverse the queue (or its values)

                                    – Marcono1234
                                    Jan 4 at 2:50














                                  1












                                  1








                                  1







                                  This is one line, but it may not be very efficient:



                                  int res = queue.stream()
                                  .collect(LinkedList<Integer>::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();


                                  If you want to be efficient and readable, you should continue using what you have now.






                                  share|improve this answer















                                  This is one line, but it may not be very efficient:



                                  int res = queue.stream()
                                  .collect(LinkedList<Integer>::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
                                  .stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();


                                  If you want to be efficient and readable, you should continue using what you have now.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 4 at 8:01









                                  ZhaoGang

                                  1,9011116




                                  1,9011116










                                  answered Jan 4 at 1:53









                                  JaiJai

                                  5,76811231




                                  5,76811231













                                  • This does not reverse the queue (or its values)

                                    – Marcono1234
                                    Jan 4 at 2:50



















                                  • This does not reverse the queue (or its values)

                                    – Marcono1234
                                    Jan 4 at 2:50

















                                  This does not reverse the queue (or its values)

                                  – Marcono1234
                                  Jan 4 at 2:50





                                  This does not reverse the queue (or its values)

                                  – Marcono1234
                                  Jan 4 at 2:50











                                  0














                                  Here is a different solution using Stream and Collections.reverse() in one line of code:



                                  Integer reversedArray = queue.stream()
                                  .collect(Collectors.collectingAndThen(Collectors.toList(),
                                  list -> {
                                  Collections.reverse(list);
                                  return list.toArray(new Integer[0]);
                                  }
                                  ));


                                  OR



                                  int reversedArray = queue.stream()
                                  .collect(Collectors.collectingAndThen(Collectors.toList(),
                                  list -> {
                                  Collections.reverse(list);
                                  return list.stream()
                                  .mapToInt(Integer::intValue)
                                  .toArray();
                                  }
                                  ));





                                  share|improve this answer






























                                    0














                                    Here is a different solution using Stream and Collections.reverse() in one line of code:



                                    Integer reversedArray = queue.stream()
                                    .collect(Collectors.collectingAndThen(Collectors.toList(),
                                    list -> {
                                    Collections.reverse(list);
                                    return list.toArray(new Integer[0]);
                                    }
                                    ));


                                    OR



                                    int reversedArray = queue.stream()
                                    .collect(Collectors.collectingAndThen(Collectors.toList(),
                                    list -> {
                                    Collections.reverse(list);
                                    return list.stream()
                                    .mapToInt(Integer::intValue)
                                    .toArray();
                                    }
                                    ));





                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      Here is a different solution using Stream and Collections.reverse() in one line of code:



                                      Integer reversedArray = queue.stream()
                                      .collect(Collectors.collectingAndThen(Collectors.toList(),
                                      list -> {
                                      Collections.reverse(list);
                                      return list.toArray(new Integer[0]);
                                      }
                                      ));


                                      OR



                                      int reversedArray = queue.stream()
                                      .collect(Collectors.collectingAndThen(Collectors.toList(),
                                      list -> {
                                      Collections.reverse(list);
                                      return list.stream()
                                      .mapToInt(Integer::intValue)
                                      .toArray();
                                      }
                                      ));





                                      share|improve this answer















                                      Here is a different solution using Stream and Collections.reverse() in one line of code:



                                      Integer reversedArray = queue.stream()
                                      .collect(Collectors.collectingAndThen(Collectors.toList(),
                                      list -> {
                                      Collections.reverse(list);
                                      return list.toArray(new Integer[0]);
                                      }
                                      ));


                                      OR



                                      int reversedArray = queue.stream()
                                      .collect(Collectors.collectingAndThen(Collectors.toList(),
                                      list -> {
                                      Collections.reverse(list);
                                      return list.stream()
                                      .mapToInt(Integer::intValue)
                                      .toArray();
                                      }
                                      ));






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 4 at 9:33

























                                      answered Jan 4 at 9:17









                                      aminographyaminography

                                      5,91321131




                                      5,91321131























                                          0














                                          Here's a way that creates a reversed array without reversing the queue:



                                          int i = { queue.size() };
                                          int array = new int[i[0]];
                                          queue.forEach(n -> array[--i[0]] = n);


                                          The above code is quite hacky due to the impossibility to modify local variables from within lambda expressions. So here i needs to be a one-element array, to overcome this restriction.



                                          Note: bear in mind that I've come to this solution just for fun :)






                                          share|improve this answer






























                                            0














                                            Here's a way that creates a reversed array without reversing the queue:



                                            int i = { queue.size() };
                                            int array = new int[i[0]];
                                            queue.forEach(n -> array[--i[0]] = n);


                                            The above code is quite hacky due to the impossibility to modify local variables from within lambda expressions. So here i needs to be a one-element array, to overcome this restriction.



                                            Note: bear in mind that I've come to this solution just for fun :)






                                            share|improve this answer




























                                              0












                                              0








                                              0







                                              Here's a way that creates a reversed array without reversing the queue:



                                              int i = { queue.size() };
                                              int array = new int[i[0]];
                                              queue.forEach(n -> array[--i[0]] = n);


                                              The above code is quite hacky due to the impossibility to modify local variables from within lambda expressions. So here i needs to be a one-element array, to overcome this restriction.



                                              Note: bear in mind that I've come to this solution just for fun :)






                                              share|improve this answer















                                              Here's a way that creates a reversed array without reversing the queue:



                                              int i = { queue.size() };
                                              int array = new int[i[0]];
                                              queue.forEach(n -> array[--i[0]] = n);


                                              The above code is quite hacky due to the impossibility to modify local variables from within lambda expressions. So here i needs to be a one-element array, to overcome this restriction.



                                              Note: bear in mind that I've come to this solution just for fun :)







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 5 at 17:06

























                                              answered Jan 5 at 16:53









                                              Federico Peralta SchaffnerFederico Peralta Schaffner

                                              22.3k43573




                                              22.3k43573






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031994%2freversing-a-queueinteger-and-converting-it-into-an-int-array%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                  Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                                  A Topological Invariant for $pi_3(U(n))$