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?
-
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); }
CookieOfFortune : There is also a Collections.sort function, but I think it does the same thing. +1 anyways.Jeremy Stein : Collections.sort takes a list as a parameter. -
sorted set:
return new TreeSet(setIWantSorted)Alex B : This was my first thought, but the asker wanted a ListJonik : @Alex: This approach can still be used; return new ArrayList(new TreeSet(setIWantSorted)) -
...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.Jeremy Stein : 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#119658Seb : 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!Michael Myers : @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!Jeremy Stein : 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. -
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; }
Jeremy Stein : Thanks! That SuppressWarnings always bothered me. -
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);
Tim : How is this different from the accepted answer?
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.