Java Reference
In-Depth Information
Solution
Use the static method Arrays.sort() or Collections.sort() , optionally providing a Com-
parator .
Discussion
If your data is in an array, then you can sort it using the static sort() method of the Arrays
utility class. If it is in a Collection , you can use the static sort() method of the Collec-
tions class. Here is a set of strings being sorted in-place in an Array :
public
public class
class SortArray
SortArray {
public
public static
void main ( String [] unused ) {
String [] strings = {
"painful" ,
"mainly" ,
"gaining" ,
"raindrops"
static void
};
Arrays . sort ( strings );
for
for ( int
int i = 0 ; i < strings . length ; i ++) {
System . out . println ( strings [ i ]);
}
}
}
What if the default sort order isn't what you want? Well, you can create an object that imple-
ments the Comparator<T> interface and pass that as the second argument to sort. For-
tunately, for the most common ordering next to the default, you don't have to: a public con-
stant String.CASE_INSENSITIVE_ORDER can be passed as this second argument. The
String class defines it as “a Comparator<String> that orders String objects as by com-
pareToIgnoreCase .” But if you need something fancier, you probably need to write a Com-
parator<T> . Suppose that, for some strange reason, you need to sort strings using all but the
first character of the string. One way to do this would be to write this Comparator<String> :
/** Comparator for comparing strings ignoring first character.
*/
public
public class
class SubstringComparator
SubstringComparator implements
implements Comparator < String > {
@Override
public
public int
int compare ( String s1 , String s2 ) {
Search WWH ::




Custom Search