Stream.sorted() then collect, or collect then List.sort()?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite
2












In general, is there a performance difference between these two pieces of code?



List<Integer> list1 = someStream1.sorted().collect(toList());
// vs.
List<Integer> list2 = someStream2.collect(toList());
list2.sort(Comparator.naturalOrder())


Variant 2 is obviously yucky and should be avoided, but I'm curious if there are any performance optimizations built into the mainstream (heh, mainstream) implementations of Stream that would result in a performance difference between these two.



I imagine that because the stream has strictly more information about the situation, it would have a better opportunity to optimize. E.g. I imagine if this had a findFirst() call tacked on, it would elide the sort, in favor of a min operation.










share|improve this question























  • This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
    – Federico Peralta Schaffner
    33 mins ago










  • @FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
    – Alexander
    31 mins ago






  • 1




    @nullpointer what do you mean? There's a List#sort method, isn't there?
    – ernest_k
    29 mins ago






  • 1




    Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
    – Federico Peralta Schaffner
    29 mins ago






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    27 mins ago














up vote
6
down vote

favorite
2












In general, is there a performance difference between these two pieces of code?



List<Integer> list1 = someStream1.sorted().collect(toList());
// vs.
List<Integer> list2 = someStream2.collect(toList());
list2.sort(Comparator.naturalOrder())


Variant 2 is obviously yucky and should be avoided, but I'm curious if there are any performance optimizations built into the mainstream (heh, mainstream) implementations of Stream that would result in a performance difference between these two.



I imagine that because the stream has strictly more information about the situation, it would have a better opportunity to optimize. E.g. I imagine if this had a findFirst() call tacked on, it would elide the sort, in favor of a min operation.










share|improve this question























  • This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
    – Federico Peralta Schaffner
    33 mins ago










  • @FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
    – Alexander
    31 mins ago






  • 1




    @nullpointer what do you mean? There's a List#sort method, isn't there?
    – ernest_k
    29 mins ago






  • 1




    Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
    – Federico Peralta Schaffner
    29 mins ago






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    27 mins ago












up vote
6
down vote

favorite
2









up vote
6
down vote

favorite
2






2





In general, is there a performance difference between these two pieces of code?



List<Integer> list1 = someStream1.sorted().collect(toList());
// vs.
List<Integer> list2 = someStream2.collect(toList());
list2.sort(Comparator.naturalOrder())


Variant 2 is obviously yucky and should be avoided, but I'm curious if there are any performance optimizations built into the mainstream (heh, mainstream) implementations of Stream that would result in a performance difference between these two.



I imagine that because the stream has strictly more information about the situation, it would have a better opportunity to optimize. E.g. I imagine if this had a findFirst() call tacked on, it would elide the sort, in favor of a min operation.










share|improve this question















In general, is there a performance difference between these two pieces of code?



List<Integer> list1 = someStream1.sorted().collect(toList());
// vs.
List<Integer> list2 = someStream2.collect(toList());
list2.sort(Comparator.naturalOrder())


Variant 2 is obviously yucky and should be avoided, but I'm curious if there are any performance optimizations built into the mainstream (heh, mainstream) implementations of Stream that would result in a performance difference between these two.



I imagine that because the stream has strictly more information about the situation, it would have a better opportunity to optimize. E.g. I imagine if this had a findFirst() call tacked on, it would elide the sort, in favor of a min operation.







java list sorting java-stream collectors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 25 mins ago

























asked 40 mins ago









Alexander

29k44474




29k44474











  • This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
    – Federico Peralta Schaffner
    33 mins ago










  • @FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
    – Alexander
    31 mins ago






  • 1




    @nullpointer what do you mean? There's a List#sort method, isn't there?
    – ernest_k
    29 mins ago






  • 1




    Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
    – Federico Peralta Schaffner
    29 mins ago






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    27 mins ago
















  • This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
    – Federico Peralta Schaffner
    33 mins ago










  • @FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
    – Alexander
    31 mins ago






  • 1




    @nullpointer what do you mean? There's a List#sort method, isn't there?
    – ernest_k
    29 mins ago






  • 1




    Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
    – Federico Peralta Schaffner
    29 mins ago






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    27 mins ago















This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
– Federico Peralta Schaffner
33 mins ago




This is a very good question. For completeness, I would add that Something implements Comparable<Something>. This way, you'd avoid answers that focus on this detail, where the heart of the question is on streaming and sorting vs sorting in place.
– Federico Peralta Schaffner
33 mins ago












@FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
– Alexander
31 mins ago




@FedericoPeraltaSchaffner Ah yes, it's good to focus the question. I changed it to Integer, so the implementation of Comparable is known. I also changed the stream names, to make it clear i'm not iterating the same stream twice (which is invalid)
– Alexander
31 mins ago




1




1




@nullpointer what do you mean? There's a List#sort method, isn't there?
– ernest_k
29 mins ago




@nullpointer what do you mean? There's a List#sort method, isn't there?
– ernest_k
29 mins ago




1




1




Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
– Federico Peralta Schaffner
29 mins ago




Also @nullpointer is right. You should use list.sort(Comparator.naturalOrder())
– Federico Peralta Schaffner
29 mins ago




4




4




@FedericoPeraltaSchaffner Or just list.sort(null).
– shmosel
27 mins ago




@FedericoPeraltaSchaffner Or just list.sort(null).
– shmosel
27 mins ago












6 Answers
6






active

oldest

votes

















up vote
3
down vote













Conceptually, streams are usually looked at as "transient" data that's being processed/manipulated, and collecting the stream conveys the notion you're done manipulating it.



While the second snippet should work, the first one would be the more idiomatic way of doing things.






share|improve this answer



























    up vote
    3
    down vote













    Both options should result in the same final result. But runtime characteristics could be different. What if the initial stream is a parallel one? Then option 1 would do a sort in parallel, whereas option 2 wouldn't do a "sequential" sort. The result should be the same, but the overall runtime resp. CPU load could be very much different then.



    I would definitely prefer option 1 over 2: why create a list first, to then later sort it?!



    Imagine for example you later want to collect into an immutable list. Then all code that follows your second pattern would break. Whereas code written using pattern 1 wouldn't be affected at all!



    Of course, in the example here that shouldn't lead to issues, but what if the sort() happens in a slightly different place?!






    share|improve this answer
















    • 2




      If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
      – Alexander
      24 mins ago

















    up vote
    2
    down vote













    In the first case the sorting happens in the call to collect. If the stream is already sorted this will be a no-op (the data will just pass through as-is). Might not make a big difference, but calling Collections.sort on an already sorted collection is still O(n).



    Also the first case benefits from parallel execution, as at least OpenJDK uses Arrays.parallelSort.



    Apart from that the first line is cleaner, better to understand and less error prone when refactoring.






    share|improve this answer



























      up vote
      1
      down vote













      The list you get back from Collectors.toList() is not guaranteed to be editable. It might be an ArrayList, or an ImmutableList, you cannot know. Therefore you must not try to modify that list.






      share|improve this answer
















      • 1




        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
        – shmosel
        25 mins ago

















      up vote
      0
      down vote













      According to documentation, it seems that the first sort is not a stable sort implementation for the unordered streams:




      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.




      but the second one is a stable sort implementation:




      This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.




      There may be some performance issues too, but according to this subject it seems that the first one may not produce a true sorted list at the end.






      share|improve this answer


















      • 2




        Did you mix up "first" and "second"?
        – Max Vollmer
        13 mins ago










      • I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
        – shmosel
        13 mins ago






      • 2




        Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
        – Radiodef
        13 mins ago


















      up vote
      -2
      down vote













      1. First, sorts your stream and returns it as a list. There is no external memory is being used.

      2. It gets the list from the stream and converts into a list and returns it. It used an external memory for the list.

      First one seems more efficient and elegant. But it all depends on the scenario/use cases.






      share|improve this answer
















      • 1




        What "external memory" are you talking about?
        – luk2302
        30 mins ago






      • 5




        1 => false. Sorting a stream requires buffering.
        – Federico Peralta Schaffner
        27 mins ago






      • 1




        If anything, I would expect the first way to require additional (temporary) memory.
        – shmosel
        24 mins ago










      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: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      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%2f52448983%2fstream-sorted-then-collect-or-collect-then-list-sort%23new-answer', 'question_page');

      );

      Post as a guest






























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      3
      down vote













      Conceptually, streams are usually looked at as "transient" data that's being processed/manipulated, and collecting the stream conveys the notion you're done manipulating it.



      While the second snippet should work, the first one would be the more idiomatic way of doing things.






      share|improve this answer
























        up vote
        3
        down vote













        Conceptually, streams are usually looked at as "transient" data that's being processed/manipulated, and collecting the stream conveys the notion you're done manipulating it.



        While the second snippet should work, the first one would be the more idiomatic way of doing things.






        share|improve this answer






















          up vote
          3
          down vote










          up vote
          3
          down vote









          Conceptually, streams are usually looked at as "transient" data that's being processed/manipulated, and collecting the stream conveys the notion you're done manipulating it.



          While the second snippet should work, the first one would be the more idiomatic way of doing things.






          share|improve this answer












          Conceptually, streams are usually looked at as "transient" data that's being processed/manipulated, and collecting the stream conveys the notion you're done manipulating it.



          While the second snippet should work, the first one would be the more idiomatic way of doing things.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 33 mins ago









          Mureinik

          166k21120181




          166k21120181






















              up vote
              3
              down vote













              Both options should result in the same final result. But runtime characteristics could be different. What if the initial stream is a parallel one? Then option 1 would do a sort in parallel, whereas option 2 wouldn't do a "sequential" sort. The result should be the same, but the overall runtime resp. CPU load could be very much different then.



              I would definitely prefer option 1 over 2: why create a list first, to then later sort it?!



              Imagine for example you later want to collect into an immutable list. Then all code that follows your second pattern would break. Whereas code written using pattern 1 wouldn't be affected at all!



              Of course, in the example here that shouldn't lead to issues, but what if the sort() happens in a slightly different place?!






              share|improve this answer
















              • 2




                If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
                – Alexander
                24 mins ago














              up vote
              3
              down vote













              Both options should result in the same final result. But runtime characteristics could be different. What if the initial stream is a parallel one? Then option 1 would do a sort in parallel, whereas option 2 wouldn't do a "sequential" sort. The result should be the same, but the overall runtime resp. CPU load could be very much different then.



              I would definitely prefer option 1 over 2: why create a list first, to then later sort it?!



              Imagine for example you later want to collect into an immutable list. Then all code that follows your second pattern would break. Whereas code written using pattern 1 wouldn't be affected at all!



              Of course, in the example here that shouldn't lead to issues, but what if the sort() happens in a slightly different place?!






              share|improve this answer
















              • 2




                If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
                – Alexander
                24 mins ago












              up vote
              3
              down vote










              up vote
              3
              down vote









              Both options should result in the same final result. But runtime characteristics could be different. What if the initial stream is a parallel one? Then option 1 would do a sort in parallel, whereas option 2 wouldn't do a "sequential" sort. The result should be the same, but the overall runtime resp. CPU load could be very much different then.



              I would definitely prefer option 1 over 2: why create a list first, to then later sort it?!



              Imagine for example you later want to collect into an immutable list. Then all code that follows your second pattern would break. Whereas code written using pattern 1 wouldn't be affected at all!



              Of course, in the example here that shouldn't lead to issues, but what if the sort() happens in a slightly different place?!






              share|improve this answer












              Both options should result in the same final result. But runtime characteristics could be different. What if the initial stream is a parallel one? Then option 1 would do a sort in parallel, whereas option 2 wouldn't do a "sequential" sort. The result should be the same, but the overall runtime resp. CPU load could be very much different then.



              I would definitely prefer option 1 over 2: why create a list first, to then later sort it?!



              Imagine for example you later want to collect into an immutable list. Then all code that follows your second pattern would break. Whereas code written using pattern 1 wouldn't be affected at all!



              Of course, in the example here that shouldn't lead to issues, but what if the sort() happens in a slightly different place?!







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 28 mins ago









              GhostCat

              82.6k1579136




              82.6k1579136







              • 2




                If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
                – Alexander
                24 mins ago












              • 2




                If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
                – Alexander
                24 mins ago







              2




              2




              If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
              – Alexander
              24 mins ago




              If the stream can support sorting and collecting into an immutable list, does that mean that the stream has its own scratch buffer where it does the sorting, and then has to do a copy?
              – Alexander
              24 mins ago










              up vote
              2
              down vote













              In the first case the sorting happens in the call to collect. If the stream is already sorted this will be a no-op (the data will just pass through as-is). Might not make a big difference, but calling Collections.sort on an already sorted collection is still O(n).



              Also the first case benefits from parallel execution, as at least OpenJDK uses Arrays.parallelSort.



              Apart from that the first line is cleaner, better to understand and less error prone when refactoring.






              share|improve this answer
























                up vote
                2
                down vote













                In the first case the sorting happens in the call to collect. If the stream is already sorted this will be a no-op (the data will just pass through as-is). Might not make a big difference, but calling Collections.sort on an already sorted collection is still O(n).



                Also the first case benefits from parallel execution, as at least OpenJDK uses Arrays.parallelSort.



                Apart from that the first line is cleaner, better to understand and less error prone when refactoring.






                share|improve this answer






















                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  In the first case the sorting happens in the call to collect. If the stream is already sorted this will be a no-op (the data will just pass through as-is). Might not make a big difference, but calling Collections.sort on an already sorted collection is still O(n).



                  Also the first case benefits from parallel execution, as at least OpenJDK uses Arrays.parallelSort.



                  Apart from that the first line is cleaner, better to understand and less error prone when refactoring.






                  share|improve this answer












                  In the first case the sorting happens in the call to collect. If the stream is already sorted this will be a no-op (the data will just pass through as-is). Might not make a big difference, but calling Collections.sort on an already sorted collection is still O(n).



                  Also the first case benefits from parallel execution, as at least OpenJDK uses Arrays.parallelSort.



                  Apart from that the first line is cleaner, better to understand and less error prone when refactoring.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 19 mins ago









                  Max Vollmer

                  5,07641234




                  5,07641234




















                      up vote
                      1
                      down vote













                      The list you get back from Collectors.toList() is not guaranteed to be editable. It might be an ArrayList, or an ImmutableList, you cannot know. Therefore you must not try to modify that list.






                      share|improve this answer
















                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        25 mins ago














                      up vote
                      1
                      down vote













                      The list you get back from Collectors.toList() is not guaranteed to be editable. It might be an ArrayList, or an ImmutableList, you cannot know. Therefore you must not try to modify that list.






                      share|improve this answer
















                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        25 mins ago












                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      The list you get back from Collectors.toList() is not guaranteed to be editable. It might be an ArrayList, or an ImmutableList, you cannot know. Therefore you must not try to modify that list.






                      share|improve this answer












                      The list you get back from Collectors.toList() is not guaranteed to be editable. It might be an ArrayList, or an ImmutableList, you cannot know. Therefore you must not try to modify that list.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 26 mins ago









                      Roland Illig

                      28.6k95590




                      28.6k95590







                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        25 mins ago












                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        25 mins ago







                      1




                      1




                      Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                      – shmosel
                      25 mins ago




                      Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                      – shmosel
                      25 mins ago










                      up vote
                      0
                      down vote













                      According to documentation, it seems that the first sort is not a stable sort implementation for the unordered streams:




                      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.




                      but the second one is a stable sort implementation:




                      This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.




                      There may be some performance issues too, but according to this subject it seems that the first one may not produce a true sorted list at the end.






                      share|improve this answer


















                      • 2




                        Did you mix up "first" and "second"?
                        – Max Vollmer
                        13 mins ago










                      • I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                        – shmosel
                        13 mins ago






                      • 2




                        Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                        – Radiodef
                        13 mins ago















                      up vote
                      0
                      down vote













                      According to documentation, it seems that the first sort is not a stable sort implementation for the unordered streams:




                      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.




                      but the second one is a stable sort implementation:




                      This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.




                      There may be some performance issues too, but according to this subject it seems that the first one may not produce a true sorted list at the end.






                      share|improve this answer


















                      • 2




                        Did you mix up "first" and "second"?
                        – Max Vollmer
                        13 mins ago










                      • I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                        – shmosel
                        13 mins ago






                      • 2




                        Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                        – Radiodef
                        13 mins ago













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      According to documentation, it seems that the first sort is not a stable sort implementation for the unordered streams:




                      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.




                      but the second one is a stable sort implementation:




                      This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.




                      There may be some performance issues too, but according to this subject it seems that the first one may not produce a true sorted list at the end.






                      share|improve this answer














                      According to documentation, it seems that the first sort is not a stable sort implementation for the unordered streams:




                      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.




                      but the second one is a stable sort implementation:




                      This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.




                      There may be some performance issues too, but according to this subject it seems that the first one may not produce a true sorted list at the end.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 4 mins ago

























                      answered 18 mins ago









                      epcpu

                      32618




                      32618







                      • 2




                        Did you mix up "first" and "second"?
                        – Max Vollmer
                        13 mins ago










                      • I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                        – shmosel
                        13 mins ago






                      • 2




                        Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                        – Radiodef
                        13 mins ago













                      • 2




                        Did you mix up "first" and "second"?
                        – Max Vollmer
                        13 mins ago










                      • I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                        – shmosel
                        13 mins ago






                      • 2




                        Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                        – Radiodef
                        13 mins ago








                      2




                      2




                      Did you mix up "first" and "second"?
                      – Max Vollmer
                      13 mins ago




                      Did you mix up "first" and "second"?
                      – Max Vollmer
                      13 mins ago












                      I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                      – shmosel
                      13 mins ago




                      I think your'e mixing up the first and second snippets. Either way, the end result is the same. If the stream is unordered, the resulting list will be unordered in the second case, so it won't help that the sort is stable.
                      – shmosel
                      13 mins ago




                      2




                      2




                      Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                      – Radiodef
                      13 mins ago





                      Sort instability doesn't mean that the result won't necessarily be sorted. It just means that two objects which are equal may be reordered with respect to each other. For example, if the input is [John Smith, Jane Smith, Joe Brown] and we sort based on last name only, an unstable sort could produce [Joe Brown, Jane Smith, John Smith].
                      – Radiodef
                      13 mins ago











                      up vote
                      -2
                      down vote













                      1. First, sorts your stream and returns it as a list. There is no external memory is being used.

                      2. It gets the list from the stream and converts into a list and returns it. It used an external memory for the list.

                      First one seems more efficient and elegant. But it all depends on the scenario/use cases.






                      share|improve this answer
















                      • 1




                        What "external memory" are you talking about?
                        – luk2302
                        30 mins ago






                      • 5




                        1 => false. Sorting a stream requires buffering.
                        – Federico Peralta Schaffner
                        27 mins ago






                      • 1




                        If anything, I would expect the first way to require additional (temporary) memory.
                        – shmosel
                        24 mins ago














                      up vote
                      -2
                      down vote













                      1. First, sorts your stream and returns it as a list. There is no external memory is being used.

                      2. It gets the list from the stream and converts into a list and returns it. It used an external memory for the list.

                      First one seems more efficient and elegant. But it all depends on the scenario/use cases.






                      share|improve this answer
















                      • 1




                        What "external memory" are you talking about?
                        – luk2302
                        30 mins ago






                      • 5




                        1 => false. Sorting a stream requires buffering.
                        – Federico Peralta Schaffner
                        27 mins ago






                      • 1




                        If anything, I would expect the first way to require additional (temporary) memory.
                        – shmosel
                        24 mins ago












                      up vote
                      -2
                      down vote










                      up vote
                      -2
                      down vote









                      1. First, sorts your stream and returns it as a list. There is no external memory is being used.

                      2. It gets the list from the stream and converts into a list and returns it. It used an external memory for the list.

                      First one seems more efficient and elegant. But it all depends on the scenario/use cases.






                      share|improve this answer












                      1. First, sorts your stream and returns it as a list. There is no external memory is being used.

                      2. It gets the list from the stream and converts into a list and returns it. It used an external memory for the list.

                      First one seems more efficient and elegant. But it all depends on the scenario/use cases.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 32 mins ago









                      Omar Faroque Anik

                      1,6211524




                      1,6211524







                      • 1




                        What "external memory" are you talking about?
                        – luk2302
                        30 mins ago






                      • 5




                        1 => false. Sorting a stream requires buffering.
                        – Federico Peralta Schaffner
                        27 mins ago






                      • 1




                        If anything, I would expect the first way to require additional (temporary) memory.
                        – shmosel
                        24 mins ago












                      • 1




                        What "external memory" are you talking about?
                        – luk2302
                        30 mins ago






                      • 5




                        1 => false. Sorting a stream requires buffering.
                        – Federico Peralta Schaffner
                        27 mins ago






                      • 1




                        If anything, I would expect the first way to require additional (temporary) memory.
                        – shmosel
                        24 mins ago







                      1




                      1




                      What "external memory" are you talking about?
                      – luk2302
                      30 mins ago




                      What "external memory" are you talking about?
                      – luk2302
                      30 mins ago




                      5




                      5




                      1 => false. Sorting a stream requires buffering.
                      – Federico Peralta Schaffner
                      27 mins ago




                      1 => false. Sorting a stream requires buffering.
                      – Federico Peralta Schaffner
                      27 mins ago




                      1




                      1




                      If anything, I would expect the first way to require additional (temporary) memory.
                      – shmosel
                      24 mins ago




                      If anything, I would expect the first way to require additional (temporary) memory.
                      – shmosel
                      24 mins ago

















                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52448983%2fstream-sorted-then-collect-or-collect-then-list-sort%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      Long meetings (6-7 hours a day): Being “babysat” by supervisor

                      Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                      Confectionery