In Java, I have a set, and I want to turn it into a sorted list. Is there a method in the collections package that will do this for me?
+1
A:
There's no single method to do that. Use this:
@SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
T[] array = collection.toArray(
(T[])new Comparable[collection.size()]);
Arrays.sort(array);
return Arrays.asList(array);
}
Jeremy Stein
2009-04-11 15:26:44
There is also a Collections.sort function, but I think it does the same thing. +1 anyways.
CookieOfFortune
2009-04-11 15:30:17
Collections.sort takes a list as a parameter.
Jeremy Stein
2009-04-11 15:47:52
+4
A:
...you answered your own question 38 seconds after you had asked it?
List myList = new ArrayList(collection);
Collections.sort(myList);
should do the trick however. Add flavour with Generics where applicable.
Esko
2009-04-11 15:30:30
I had a useful snippet I wanted to donate to the community. When I searched for the information, I couldn't find it. I was trying to make the next person's job easier.http://stackoverflow.com/questions/18557/how-does-stackoverflow-work-the-unofficial-faq#119658
Jeremy Stein
2009-04-11 15:46:27
Yeah, sure, but that link you provided is actually talking about a _real_ questions (i.e. those for which don't have the answer, then find it). Your question here was only to give the answer... I could actually enter hundreds of questions and answer myself; that's not the point!
Seb
2009-04-11 16:10:14
@Seb: I disagree. I don't see anything wrong with this question. It obviously wasn't an extremely simple question, and now he knows a better way than he did before!
Michael Myers
2009-04-11 16:56:33
It *was* a real question, but I found the answer myself after Google came up short. Stackoverflow didn't exist at the time. I had it posted on my website and it helped someone else, so I thought it might be useful here.
Jeremy Stein
2009-04-13 18:40:21
+15
A:
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);
java.util.Collections.sort(list);
return list;
}
erickson
2009-04-11 16:06:02
A:
You can convert a set into a ArrayList. where you can sort ArrayList using Collections.sort(List);
here is the code..
keySet = (Set) map.keySet();
System.out.println("key Set -----------------------> " + keySet);
ArrayList list = new ArrayList(keySet);
System.out.println("List ----------------------> "+ list);
Collections.sort(list);
Amit
2010-06-11 05:51:24