Search

Wednesday, September 9, 2015

How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort an HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have an HashSet then how would I go about sorting it? Answer is you cannot sort an HashSet, why? because HashSet is an un-ordered collection. When you insert element in HashSet than you lose the order guarantee. You cannot do re-ordering or sorting in Set because it does not have random access methods (ie, .get() an element at a given index), which is basically required for sort algorithms. Though you can sort the HashSet by first converting HashSet to List and then sorting it. Also, some of Set implementation may keep the order intact e.g. LinkedHashSet maintains insertion order, which means you can sort LinkedHashSet but not HashSet. Alternatively you can also use TreeSet to keep elements in the sorted order from start. In short, you cannot sort HashSet directly but you can do so by converting it into List and then sorting a List and accessing elements from it in sorted order for further processing. If you are new in Java and wants to learn Java Collection framework in deep, then you can also check Java Generics and Collection book, one of the best on generics and collection.
Read more »

No comments:

Post a Comment