Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorted copy construction for ArrayList

I have an ArrayList.
How can I instantiate a new List with the same data but sorted?
I thought about the following:

  1. Use the ArrayList copy constructor and then use Collections.sort
  2. Use a 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?

like image 205
Jim Avatar asked Nov 28 '22 16:11

Jim


1 Answers

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

like image 79
Louis Wasserman Avatar answered Dec 04 '22 12:12

Louis Wasserman