Is it somehow possible to iterate over a collection sorting the content on the fly without creating a copy?
UPDATE: Collection to sort is a read-only list.
Using the Streams API you could do
yourCollection.stream()
.sorted(yourComparator)
.forEach(...);
This does not modify yourCollection and allows you to iterate over the collection in a sorted order. However, chances are that the sorted method creates a copy behind the scenes, so you'll most likely get the same memory/cpu overhead as if you create a copy, sort the copy and iterate over the sorted copy yourself.
(For Java 7 and earlier, I don't think there's a "non-intrusive" sorting method in the API. You'll have to explicitly make a copy if you don't want to modify the original collection.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With