What are the different ways of performing sorting in java
This question was asked in an intervie开发者_开发百科w . Except Collections.sort() what are the other methods .
Sorting Interfaces
Comparable<T>
and Comparator<T>
are the standard interfaces used by all standard Java sorting options (all except those on primitive arrays, that is).
In Java-speak, any Class that implements Comparable has a "natural order". (Technically, it must implement Comparable<? super E>
where E matches itself, to have a natural order). Classes that don't have a natural order can be sorted using an external Comparator. A Comparator can also be used to implement a sort order that runs against the natural order (e.g. sort Strings in descending alphabetic order).
These principles are applied both in the SortedSet<E>
and SortedMap<K,V>
implementations, that sort their elements / keys automatically using either the natural order or a supplied comparator.
These same principles can also be found in the static Utility methods
Arrays.sort(arr)
andArrays.sort(arr, comparator)
for ArraysCollections.sort(list)
andCollections.sort(list, comparator)
for Lists
that can be used to sort arrays and lists, respectively, each of which don't support sorting themselves.
Guava
The Guava Library takes this a bit further by providing the abstract Ordering
class as base implementation of Comparator
which already contains standard methods like providing a reverse view of itself and many convenience methods for sorting and retrieving based on this Ordering
.
Reference
A good article about Object Ordering can be found in the Sun Java Tutorial's Collection Trail.
- SortedSet or SortedMap, provided the keys are unique.
- PriorityQueue.
- Arrays.sort().
- Own code.
- A JDBC query with an ORDER BY clause.
- An LDAP search against an indexed attribute.
I'm sure there are more.
- Insertion Sort is used for small size arrays.
- Dual Pivot Quick Sort is used for larger size arrays.
- MergeSort is used for sorting object.
Arrays.sort(..)
, or implement sorting yourself.
You can stick your data into a SortedSet
(e.g. TreeSet
) and pull it out again in sorted order by traversing with an iterator. This is not really a general sorting method (since it doesn't allow duplicated entries), but would work for quite a lot of data set.
精彩评论