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
Sorted() Method This is a pre-defined method in python which sorts any kind of object. In this method, we pass 3 parameters, out of which 2 (key and reverse) are optional and the first parameter i.e. iterable can be any iterable object This method returns a sorted list but does not change the original data structure.
sort() established the convention that sort() sorts the object in place, but a set cannot be sorted in place because sets are unordered.
set 's are unordered. They don't have an order. You could use OrderedDict or just dict in Python 3.7+ if you like.
sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.
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:
SortedSet
interfaceTreeSet
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With