Jeremy Stein Jeremy Stein - 1 year ago 104
Java Question

How do I sort a Set to a List in Java?

In Java, I have a

, and I want to turn it into a sorted
. Is there a method in the
package that will do this for me?

Answer Source

The answer provided by the OP is not the best. It is inefficient, as it creates a new List and an unnecessary new array. Also, it raises "unchecked" warnings because of the type safety issues around generic arrays.

Instead, use something like this:

public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
  List<T> list = new ArrayList<T>(c);
  return list;

Here's a usage example:

Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download