Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collections. Creating a sorted view without creating a copy

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.

like image 353
30thh Avatar asked Dec 01 '25 02:12

30thh


1 Answers

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.)

like image 154
aioobe Avatar answered Dec 02 '25 14:12

aioobe