Sorting Values of Set
Use a SortedSet (TreeSet is the default one):
SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);
No extra sorting code needed.
Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:
new TreeSet<String>(Comparator.comparing(Integer::valueOf));
Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)
Reference:
- Java Tutorial (Collections Trail):
- Object Ordering
- The
SortedSet
interface
- Javadocs:
TreeSet
- Javadocs:
Comparator
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.
Collections.sort(list, new Comparator<String>() {
public int compare(String o1, String o2) {
Integer i1 = Integer.parseInt(o1);
Integer i2 = Integer.parseInt(o2);
return (i1 > i2 ? -1 : (i1 == i2 ? 0 : 1));
}
});
Also, I think you are getting slightly mixed up between Collection
types. A HashSet
and a HashMap
are different things.