Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a LinkedHashSet

Tags:

java

sorting

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?

like image 727
Matthew Brzezinski Avatar asked Jun 28 '13 17:06

Matthew Brzezinski


People also ask

Is LinkedHashSet sorted by default?

A LinkedHashSet preserves order based on insertion order. but that's probably not the best approach.

Does LinkedHashSet maintain order?

Yes, the order is preserved in case the incoming collection is ordered.

How seq order is preserved in LinkedHashSet?

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.

Is sorting possible in HashSet?

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.


Video Answer


2 Answers

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.

like image 144
Emil Sit Avatar answered Oct 21 '22 12:10

Emil Sit


Collections.sort does not work on Sets, only on Lists. If you need to sort the data that is already in a Set, you might want to first add them into a List.

like image 4
zw324 Avatar answered Oct 21 '22 11:10

zw324