I am trying to sort elements of a set but unable to do so far.
here is my code which i am trying to do
public static void main(String [] args){
Set<String> set=new HashSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=asSortedList(set);
}
public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
List<T> list = new ArrayList<T>(c);
Collections.sort(list);
return list;
}
but this or other way is not working since its all time giving me the same order in which they have been filled
12,15,5
If you sort the strings
"12","15"and"5"then"5"comes last because"5">"1". i.e. the natural ordering of Strings doesn’t work the way you expect.If you want to store strings in your list but sort them numerically then you will need to use a comparator that handles this. e.g.
Also, I think you are getting slightly mixed up between
Collectiontypes. AHashSetand aHashMapare different things.