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.
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.)
Let's say you're trying to iterate through the sorted version of a collection.
What's the first element? The minimum element.
But you have to read through the entire collection to determine the minimum element, or there's no guarantee you haven't missed some element that comes later that's smaller than everything before it.
That more or less means you have to make a copy: you have to have read the whole collection before you can start returning elements, after which starting to read it again is kind of redundant.