Reverse Sort a stream











up vote
7
down vote

favorite












I want to reverse sort a stream such as below but getting compile time error as "The method sorted() in the type IntStream is not applicable for the arguments ((<no type> o1, <no type> o2) -> {})". Can anyone correct this



IntStream.range(1, 100)
.filter(x -> x%2 != 0)
.sorted((o1,o2) -> -o1.compareTo(o2))
.forEach(System.out::println);









share|improve this question




















  • 5




    I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
    – JimmyJames
    13 hours ago















up vote
7
down vote

favorite












I want to reverse sort a stream such as below but getting compile time error as "The method sorted() in the type IntStream is not applicable for the arguments ((<no type> o1, <no type> o2) -> {})". Can anyone correct this



IntStream.range(1, 100)
.filter(x -> x%2 != 0)
.sorted((o1,o2) -> -o1.compareTo(o2))
.forEach(System.out::println);









share|improve this question




















  • 5




    I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
    – JimmyJames
    13 hours ago













up vote
7
down vote

favorite









up vote
7
down vote

favorite











I want to reverse sort a stream such as below but getting compile time error as "The method sorted() in the type IntStream is not applicable for the arguments ((<no type> o1, <no type> o2) -> {})". Can anyone correct this



IntStream.range(1, 100)
.filter(x -> x%2 != 0)
.sorted((o1,o2) -> -o1.compareTo(o2))
.forEach(System.out::println);









share|improve this question















I want to reverse sort a stream such as below but getting compile time error as "The method sorted() in the type IntStream is not applicable for the arguments ((<no type> o1, <no type> o2) -> {})". Can anyone correct this



IntStream.range(1, 100)
.filter(x -> x%2 != 0)
.sorted((o1,o2) -> -o1.compareTo(o2))
.forEach(System.out::println);






java sorting java-8 java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago









user2357112

149k12155243




149k12155243










asked 15 hours ago









Sundresh

672




672








  • 5




    I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
    – JimmyJames
    13 hours ago














  • 5




    I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
    – JimmyJames
    13 hours ago








5




5




I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
– JimmyJames
13 hours ago




I'm curious as to why you would use streams for something like this. It would seem to only add a bunch of overhead.
– JimmyJames
13 hours ago












3 Answers
3






active

oldest

votes

















up vote
11
down vote













Explanation



since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).



instead, box the stream from IntStream to Stream<Integer> then it should suffice:



 IntStream.range(1, 100)
.filter(x -> x % 2 != 0)
.boxed() // <--- boxed to Stream<Integer>
.sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
.forEach(System.out::println);


However, as mentioned by @Holger in the comments:




never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
is perfectly legal for a compareTo implementation to return
Integer.MIN_VALUE, in which case negation will fail and produce
inconsistent results. A valid reverse comparator would be (o1,o2) ->
o2.compareTo(o1)




Suggestions to improve your code. JDK8



A better approach would be:



IntStream.range(1, 100)
.filter(x -> x % 2 != 0)
.boxed()
.sorted(Comparator.reverseOrder())
.forEachOrdered(System.out::println);


why?




  • There's already a built-in comparator to perform reverse order as shown above.

  • if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)


or as suggested by @Holger it can all be simplified to as little as this:



 IntStream.range(0, 50)
.map(i -> 99-i*2)
.forEachOrdered(System.out::println);


JDK9 variant



btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:



IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
.boxed()
.sorted(Comparator.reverseOrder())
.forEachOrdered(System.out::println);


With this approach, we can avoid the filter intermediate operation and increment in 2's.



and finally you could simplify it even further with:



IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
.forEachOrdered(System.out::println);


With this approach, we can avoid filter, boxed,sorted et al.






share|improve this answer



















  • 3




    When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
    – Holger
    13 hours ago






  • 1




    @Holger really appreciated, learning as always. edited to accommodate your recommendations.
    – Aomine
    13 hours ago


















up vote
4
down vote













If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:



IntStream.iterate(99, i -> i - 1)
.limit(100)
.filter(x -> x % 2 != 0)
.forEachOrdered(System.out::println);





share|improve this answer




























    up vote
    4
    down vote













    How about simple util such as :



    private IntStream reverseSort(int from, int to) {
    return IntStream.range(from, to)
    .filter(x -> x % 2 != 0)
    .sorted()
    .map(i -> to - i + from - 1);
    }


    Credits: Stuart Marks for the reverse util.






    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',
      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%2f53764661%2freverse-sort-a-stream%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      11
      down vote













      Explanation



      since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).



      instead, box the stream from IntStream to Stream<Integer> then it should suffice:



       IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed() // <--- boxed to Stream<Integer>
      .sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
      .forEach(System.out::println);


      However, as mentioned by @Holger in the comments:




      never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
      is perfectly legal for a compareTo implementation to return
      Integer.MIN_VALUE, in which case negation will fail and produce
      inconsistent results. A valid reverse comparator would be (o1,o2) ->
      o2.compareTo(o1)




      Suggestions to improve your code. JDK8



      A better approach would be:



      IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      why?




      • There's already a built-in comparator to perform reverse order as shown above.

      • if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)


      or as suggested by @Holger it can all be simplified to as little as this:



       IntStream.range(0, 50)
      .map(i -> 99-i*2)
      .forEachOrdered(System.out::println);


      JDK9 variant



      btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:



      IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      With this approach, we can avoid the filter intermediate operation and increment in 2's.



      and finally you could simplify it even further with:



      IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
      .forEachOrdered(System.out::println);


      With this approach, we can avoid filter, boxed,sorted et al.






      share|improve this answer



















      • 3




        When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
        – Holger
        13 hours ago






      • 1




        @Holger really appreciated, learning as always. edited to accommodate your recommendations.
        – Aomine
        13 hours ago















      up vote
      11
      down vote













      Explanation



      since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).



      instead, box the stream from IntStream to Stream<Integer> then it should suffice:



       IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed() // <--- boxed to Stream<Integer>
      .sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
      .forEach(System.out::println);


      However, as mentioned by @Holger in the comments:




      never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
      is perfectly legal for a compareTo implementation to return
      Integer.MIN_VALUE, in which case negation will fail and produce
      inconsistent results. A valid reverse comparator would be (o1,o2) ->
      o2.compareTo(o1)




      Suggestions to improve your code. JDK8



      A better approach would be:



      IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      why?




      • There's already a built-in comparator to perform reverse order as shown above.

      • if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)


      or as suggested by @Holger it can all be simplified to as little as this:



       IntStream.range(0, 50)
      .map(i -> 99-i*2)
      .forEachOrdered(System.out::println);


      JDK9 variant



      btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:



      IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      With this approach, we can avoid the filter intermediate operation and increment in 2's.



      and finally you could simplify it even further with:



      IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
      .forEachOrdered(System.out::println);


      With this approach, we can avoid filter, boxed,sorted et al.






      share|improve this answer



















      • 3




        When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
        – Holger
        13 hours ago






      • 1




        @Holger really appreciated, learning as always. edited to accommodate your recommendations.
        – Aomine
        13 hours ago













      up vote
      11
      down vote










      up vote
      11
      down vote









      Explanation



      since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).



      instead, box the stream from IntStream to Stream<Integer> then it should suffice:



       IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed() // <--- boxed to Stream<Integer>
      .sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
      .forEach(System.out::println);


      However, as mentioned by @Holger in the comments:




      never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
      is perfectly legal for a compareTo implementation to return
      Integer.MIN_VALUE, in which case negation will fail and produce
      inconsistent results. A valid reverse comparator would be (o1,o2) ->
      o2.compareTo(o1)




      Suggestions to improve your code. JDK8



      A better approach would be:



      IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      why?




      • There's already a built-in comparator to perform reverse order as shown above.

      • if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)


      or as suggested by @Holger it can all be simplified to as little as this:



       IntStream.range(0, 50)
      .map(i -> 99-i*2)
      .forEachOrdered(System.out::println);


      JDK9 variant



      btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:



      IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      With this approach, we can avoid the filter intermediate operation and increment in 2's.



      and finally you could simplify it even further with:



      IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
      .forEachOrdered(System.out::println);


      With this approach, we can avoid filter, boxed,sorted et al.






      share|improve this answer














      Explanation



      since you're working with an IntStream it only has one overload of the sorted method and it's the natural order (which makes sense).



      instead, box the stream from IntStream to Stream<Integer> then it should suffice:



       IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed() // <--- boxed to Stream<Integer>
      .sorted((o1,o2) -> -o1.compareTo(o2)) // now we can call compareTo on Integer
      .forEach(System.out::println);


      However, as mentioned by @Holger in the comments:




      never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It
      is perfectly legal for a compareTo implementation to return
      Integer.MIN_VALUE, in which case negation will fail and produce
      inconsistent results. A valid reverse comparator would be (o1,o2) ->
      o2.compareTo(o1)




      Suggestions to improve your code. JDK8



      A better approach would be:



      IntStream.range(1, 100)
      .filter(x -> x % 2 != 0)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      why?




      • There's already a built-in comparator to perform reverse order as shown above.

      • if you want to guarantee that the elements are to be seen in the sorted order when printing then utilise forEachOrdered (big shout out to @Holger for always reminding me)


      or as suggested by @Holger it can all be simplified to as little as this:



       IntStream.range(0, 50)
      .map(i -> 99-i*2)
      .forEachOrdered(System.out::println);


      JDK9 variant



      btw, in JDK9 starting from the code in your post, you can first simplify it via iterate to:



      IntStream.iterate(1, i  -> i <= 99, i -> i + 2)
      .boxed()
      .sorted(Comparator.reverseOrder())
      .forEachOrdered(System.out::println);


      With this approach, we can avoid the filter intermediate operation and increment in 2's.



      and finally you could simplify it even further with:



      IntStream.iterate(99, i  -> i > 0 , i -> i - 2)
      .forEachOrdered(System.out::println);


      With this approach, we can avoid filter, boxed,sorted et al.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 13 hours ago

























      answered 15 hours ago









      Aomine

      36.1k62961




      36.1k62961








      • 3




        When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
        – Holger
        13 hours ago






      • 1




        @Holger really appreciated, learning as always. edited to accommodate your recommendations.
        – Aomine
        13 hours ago














      • 3




        When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
        – Holger
        13 hours ago






      • 1




        @Holger really appreciated, learning as always. edited to accommodate your recommendations.
        – Aomine
        13 hours ago








      3




      3




      When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
      – Holger
      13 hours ago




      When we are at usual reminders, never use a comparator function like (o1,o2) -> -o1.compareTo(o2). It is perfectly legal for a compareTo implementation to return Integer.MIN_VALUE, in which case negation will fail and produce inconsistent results. A valid reverse comparator would be (o1,o2) -> o2.compareTo(o1), or just Comparator.reverseOrder() as you have shown, which does already the job right. By the way, I wouldn’t use iterate but rather IntStream.range(0, 50).map(i -> 99-i*2) which is more efficient in a lot of cases.
      – Holger
      13 hours ago




      1




      1




      @Holger really appreciated, learning as always. edited to accommodate your recommendations.
      – Aomine
      13 hours ago




      @Holger really appreciated, learning as always. edited to accommodate your recommendations.
      – Aomine
      13 hours ago












      up vote
      4
      down vote













      If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:



      IntStream.iterate(99, i -> i - 1)
      .limit(100)
      .filter(x -> x % 2 != 0)
      .forEachOrdered(System.out::println);





      share|improve this answer

























        up vote
        4
        down vote













        If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:



        IntStream.iterate(99, i -> i - 1)
        .limit(100)
        .filter(x -> x % 2 != 0)
        .forEachOrdered(System.out::println);





        share|improve this answer























          up vote
          4
          down vote










          up vote
          4
          down vote









          If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:



          IntStream.iterate(99, i -> i - 1)
          .limit(100)
          .filter(x -> x % 2 != 0)
          .forEachOrdered(System.out::println);





          share|improve this answer












          If that is your real code, then it may be more efficient to use IntStream.iterate and generate numbers from 99 to 0:



          IntStream.iterate(99, i -> i - 1)
          .limit(100)
          .filter(x -> x % 2 != 0)
          .forEachOrdered(System.out::println);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 15 hours ago









          ernest_k

          18.8k41839




          18.8k41839






















              up vote
              4
              down vote













              How about simple util such as :



              private IntStream reverseSort(int from, int to) {
              return IntStream.range(from, to)
              .filter(x -> x % 2 != 0)
              .sorted()
              .map(i -> to - i + from - 1);
              }


              Credits: Stuart Marks for the reverse util.






              share|improve this answer



























                up vote
                4
                down vote













                How about simple util such as :



                private IntStream reverseSort(int from, int to) {
                return IntStream.range(from, to)
                .filter(x -> x % 2 != 0)
                .sorted()
                .map(i -> to - i + from - 1);
                }


                Credits: Stuart Marks for the reverse util.






                share|improve this answer

























                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  How about simple util such as :



                  private IntStream reverseSort(int from, int to) {
                  return IntStream.range(from, to)
                  .filter(x -> x % 2 != 0)
                  .sorted()
                  .map(i -> to - i + from - 1);
                  }


                  Credits: Stuart Marks for the reverse util.






                  share|improve this answer














                  How about simple util such as :



                  private IntStream reverseSort(int from, int to) {
                  return IntStream.range(from, to)
                  .filter(x -> x % 2 != 0)
                  .sorted()
                  .map(i -> to - i + from - 1);
                  }


                  Credits: Stuart Marks for the reverse util.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 14 hours ago

























                  answered 14 hours ago









                  nullpointer

                  38.3k1073146




                  38.3k1073146






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53764661%2freverse-sort-a-stream%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

                      Ellipse (mathématiques)

                      Quarter-circle Tiles

                      Mont Emei