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

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











up vote
8
down vote

favorite
2













This question already has an answer here:



  • What is more efficient: sorted stream or sorting a list?

    3 answers



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















marked as duplicate by nullpointer java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Sep 21 at 18:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • @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
    Sep 21 at 18:12






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    Sep 21 at 18:17










  • @shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
    – nullpointer
    Sep 21 at 18:27






  • 1




    IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
    – nullpointer
    Sep 21 at 18:42















up vote
8
down vote

favorite
2













This question already has an answer here:



  • What is more efficient: sorted stream or sorting a list?

    3 answers



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















marked as duplicate by nullpointer java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Sep 21 at 18:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • @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
    Sep 21 at 18:12






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    Sep 21 at 18:17










  • @shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
    – nullpointer
    Sep 21 at 18:27






  • 1




    IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
    – nullpointer
    Sep 21 at 18:42













up vote
8
down vote

favorite
2









up vote
8
down vote

favorite
2






2






This question already has an answer here:



  • What is more efficient: sorted stream or sorting a list?

    3 answers



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 question already has an answer here:



  • What is more efficient: sorted stream or sorting a list?

    3 answers



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.





This question already has an answer here:



  • What is more efficient: sorted stream or sorting a list?

    3 answers







java list sorting java-stream collectors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 21 at 18:19

























asked Sep 21 at 18:03









Alexander

29.3k44474




29.3k44474




marked as duplicate by nullpointer java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Sep 21 at 18:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by nullpointer java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Sep 21 at 18:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • @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
    Sep 21 at 18:12






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    Sep 21 at 18:17










  • @shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
    – nullpointer
    Sep 21 at 18:27






  • 1




    IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
    – nullpointer
    Sep 21 at 18:42

















  • @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
    Sep 21 at 18:12






  • 4




    @FedericoPeraltaSchaffner Or just list.sort(null).
    – shmosel
    Sep 21 at 18:17










  • @shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
    – nullpointer
    Sep 21 at 18:27






  • 1




    IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
    – nullpointer
    Sep 21 at 18:42
















@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
Sep 21 at 18:12




@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
Sep 21 at 18:12




4




4




@FedericoPeraltaSchaffner Or just list.sort(null).
– shmosel
Sep 21 at 18:17




@FedericoPeraltaSchaffner Or just list.sort(null).
– shmosel
Sep 21 at 18:17












@shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
– nullpointer
Sep 21 at 18:27




@shmosel that's interesting, thanks...never noticed that this was valid as well..thought that would throw a NullPointerException :)
– nullpointer
Sep 21 at 18:27




1




1




IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
– nullpointer
Sep 21 at 18:42





IMHO, the answer by Stephen really makes more sense to understand the difference What is more efficient: sorted stream or sorting a list?. Also, since the benchmarks are also there in the linked question, I would vote to mark this as a duplicate. (which i am pretty sure not many people would second :D )
– nullpointer
Sep 21 at 18:42













5 Answers
5






active

oldest

votes

















up vote
3
down vote



accepted










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
    Sep 21 at 18:19






  • 1




    @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
    – Holger
    Sep 22 at 10:23

















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













    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
        Sep 21 at 18:19

















      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.




      So, the stability of the sort algorithm is one of the differences between these two lists sort methods.






      share|improve this answer






















      • 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
        Sep 21 at 18:30






      • 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
        Sep 21 at 18:31











      • thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
        – epcpu
        Sep 21 at 18:48

















      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      3
      down vote



      accepted










      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
        Sep 21 at 18:19






      • 1




        @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
        – Holger
        Sep 22 at 10:23














      up vote
      3
      down vote



      accepted










      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
        Sep 21 at 18:19






      • 1




        @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
        – Holger
        Sep 22 at 10:23












      up vote
      3
      down vote



      accepted







      up vote
      3
      down vote



      accepted






      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 Sep 21 at 18:15









      GhostCat

      83.3k1579136




      83.3k1579136







      • 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
        Sep 21 at 18:19






      • 1




        @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
        – Holger
        Sep 22 at 10:23












      • 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
        Sep 21 at 18:19






      • 1




        @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
        – Holger
        Sep 22 at 10:23







      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
      Sep 21 at 18:19




      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
      Sep 21 at 18:19




      1




      1




      @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
      – Holger
      Sep 22 at 10:23




      @Alexander correct, the current Stream implementation always use an internal buffer for sorting, which implies that the second variant will be slightly faster if you ensure that the result list is mutable and has in-place sorting support. Since Collectors.toList() guarantees neither, you have to use Collectors.toCollection(ArrayList::new) instead. But this precludes benefiting from potential future improvements made to Collectors.toList(). And you should not overestimate the copying costs. Before Java 8, Collections.sort always did two copying operations and almost nobody noticed…
      – Holger
      Sep 22 at 10:23












      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 Sep 21 at 18:10









          Mureinik

          169k21121185




          169k21121185




















              up vote
              3
              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
                3
                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
                  3
                  down vote










                  up vote
                  3
                  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 Sep 21 at 18:25









                  Max Vollmer

                  5,59541337




                  5,59541337




















                      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
                        Sep 21 at 18:19














                      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
                        Sep 21 at 18:19












                      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 Sep 21 at 18:17









                      Roland Illig

                      28.7k95690




                      28.7k95690







                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        Sep 21 at 18:19












                      • 1




                        Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                        – shmosel
                        Sep 21 at 18:19







                      1




                      1




                      Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                      – shmosel
                      Sep 21 at 18:19




                      Good point, but a technicality. You can do toCollection(ArrayList::new) to get a mutable list.
                      – shmosel
                      Sep 21 at 18:19










                      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.




                      So, the stability of the sort algorithm is one of the differences between these two lists sort methods.






                      share|improve this answer






















                      • 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
                        Sep 21 at 18:30






                      • 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
                        Sep 21 at 18:31











                      • thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                        – epcpu
                        Sep 21 at 18:48














                      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.




                      So, the stability of the sort algorithm is one of the differences between these two lists sort methods.






                      share|improve this answer






















                      • 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
                        Sep 21 at 18:30






                      • 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
                        Sep 21 at 18:31











                      • thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                        – epcpu
                        Sep 21 at 18:48












                      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.




                      So, the stability of the sort algorithm is one of the differences between these two lists sort methods.






                      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.




                      So, the stability of the sort algorithm is one of the differences between these two lists sort methods.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Sep 21 at 18:45

























                      answered Sep 21 at 18:26









                      epcpu

                      33119




                      33119











                      • 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
                        Sep 21 at 18:30






                      • 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
                        Sep 21 at 18:31











                      • thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                        – epcpu
                        Sep 21 at 18:48
















                      • 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
                        Sep 21 at 18:30






                      • 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
                        Sep 21 at 18:31











                      • thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                        – epcpu
                        Sep 21 at 18:48















                      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
                      Sep 21 at 18:30




                      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
                      Sep 21 at 18:30




                      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
                      Sep 21 at 18:31





                      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
                      Sep 21 at 18:31













                      thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                      – epcpu
                      Sep 21 at 18:48




                      thanks for all your comments, my friends. I have applied some changes to my answer according to your mentioned points.
                      – epcpu
                      Sep 21 at 18:48


                      Popular posts from this blog

                      Peggy Mitchell

                      Palaiologos

                      The Forum (Inglewood, California)