While analyzing the source code of many open source Java projects, I found that most developers sort in only two different ways. One of them is based on the use of the
sort()
class method Collections
or Arrays
, and the other on the use of self-sorting data structures such as TreeMap
and TreeSet
.
Using the sort() Method
If you need to sort a collection, then use theCollections.sort()
.
// Collections.sort(…)
List<ObjectName> list = new ArrayList<ObjectName>();
Collections.sort(list, new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString());
}
});
If you want to sort an array, use the Arrays.sort()
.
// Arrays.sort(…)
ObjectName[] arr = new ObjectName[10];
Arrays.sort(arr, new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString());
}
});
The method sort()
is very handy when the collection or array is already filled with values.
Using self-sorting data structures
If you need to sort a list (List
) or a set ( Set
), use a structure TreeSet
to sort.
// TreeSet
Set<ObjectName> sortedSet = new TreeSet<ObjectName>(new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString());
}
});
sortedSet.addAll(unsortedSet);
If you need to sort a dictionary ( Map
), use a TreeMap
sort structure. TreeMap
sorted by key ( key
).
// TreeMap – использующий String ключи и компаратор (Comparator) CASE_INSENSITIVE_ORDER,
// упорядочивающий строки (String) методом compareToIgnoreCase
Map<String, Integer> sortedMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
sortedMap.putAll(unsortedMap);
//TreeMap – общий случай, компаратор указывается вручную
Map<ObjectName, String> sortedMap = new TreeMap<ObjectName, String>(new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString());
}
});
sortedMap.putAll(unsortedMap);
The above approach is very useful when you need to do a lot of searching for items in a collection. Self-sorting data structures have an efficiency O(log(n))
that is better than O(n)
. This means that doubling the amount of data in the collection does not double the lookup time, but increases it by a constant amount .
Bad approach to sorting problem
Until now, you can find examples when programmers independently describe sorting algorithms. Consider the sort code below (sorting a double array in ascending order ) . This code is not only inefficient, but also not readable. And there are many such examples.double t;
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
if (r[j] < r[i]) {
t = r[i];
r[i] = r[j];
r[j] = t;
}
GO TO FULL VERSION