I have an ArrayList
.
How can I instantiate a new List
with the same data but sorted?
I thought about the following:
ArrayList
copy constructor and then use Collections.sort
TreeSet
For option (1) there is the extra overhead of copying the elements and then sorting.
For option (2) duplicates will be removed.
What is the best way for this?
If you can use third-party libraries, then with Guava this is just
List<Foo> sortedCopy = Ordering.from(comparator).sortedCopy(list);
(Disclosure: I contribute to Guava.)
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