I'm wondering if it's possible to sort a LinkedHashSet. I've tried the statement
Collections.sort((List<Comparable> paragraph);
However, that just throws an error that it cannot be casted into a List. Is there a way of doing this, or should I use another Data Structure?
A LinkedHashSet preserves order based on insertion order. but that's probably not the best approach.
Yes, the order is preserved in case the incoming collection is ordered.
HashSet doesn't follow any order where as LinkedHashSet maintains insertion order. HashSet uses HashMap object internally to store it's elements where as LinkedHashSet uses LinkedHashMap object internally to store and process it's elements.
Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.
You should use a SortedSet
such as TreeSet
or ConcurrentSkipListSet
if you care about ordering based on comparison (e.g., sorted order).
A LinkedHashSet
preserves order based on insertion order.
If you really want to use Collections.sort
you can convert the LHS into a List by actually constructing a List
(though the question doesn't tell us the type of paragraph
so I'll assume it is String
)
List<String> listParagraph = new ArrayList<String>(paragraph);
Collections.sort(listParagraph)
but that's probably not the best approach.
Collections.sort does not work on Set
s, only on List
s. If you need to sort the data that is already in a Set
, you might want to first add them into a List
.
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