在java 里,有一些内置的比较器,比如CaseInsensitiveComparator ,ReverseComparator。利用这两个内置的比较器可以完成一些另外的排序需求:比如String 忽略大小写排序,反向排序,及这两者组合的排序。
CaseInsensitiveComparator 这个比较器定义在String类里,是一个嵌套类。
下面是它的源代码类定义
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable
ReverseComparator 是定义在Collections 里。
private static class ReverseComparator
implements Comparator<Comparable<Object>>, Serializable
下面是使用这两个比较器的例子:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String[] args) {
testSort();
}
public static void testSort(){
// use the jdk provided Comparator sorting
String[] strArray = new String[]{"hello","Hello","java","Java"};
// using the normal sort
Arrays.sort(strArray);
display(strArray,"Normal");
// sort with ignoring the case sensitive
Arrays.sort(strArray,String.CASE_INSENSITIVE_ORDER);
display(strArray,"CaseInsensitive");
// reverse the order
Arrays.sort(strArray, Collections.reverseOrder());
display(strArray,"Reverse");
// reverse the ignore case sensitive order
Arrays.sort(strArray, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
display(strArray,"Reverse Insen");
}
public static void display(String[] strArray,String method){
System.out.println("Sorting Result using "+ method);
for(String string:strArray){
System.out.println(string);
}
}
}
运行结果:
Sorting Result using Normal
Hello
Java
hello
java
Sorting Result using CaseInsensitive
Hello
hello
Java
java
Sorting Result using Reverse
java
hello
Java
Hello
Sorting Result using Reverse Insen
java
Java
hello
Hello