使用Lambda来简化匿名内部类的使用
String[] names = {"Leoo", "Leo", "Leooo"};
System.out.println("未排序之前:");
for (String name : names) {
System.out.println(name);
}
Arrays.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
System.out.println("排序后:");
for (String name : names) {
System.out.println(name);
}
-
运行结果
未排序之前:
Leoo
Leo
Leooo
排序后:
Leo
Leoo
Leooo
-
或者新建一个比较器,这样可以在别的地方复用
Comparator<String> ByLength = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
Arrays.sort(names, ByLength);
-
使用Lambda简化
Comparator<String> ByLength = (String o1, String o2) -> o1.length() - o2.length();
Arrays.sort(names, (o1, o2) -> o1.length() - o2.length());
方法参考
public class StringOrder {
public static int ByLength(String o1, String o2) {
return o1.length() - o2.length();
}
public static int ByZD(String o1, String o2) {
return o1.compareTo(o2);
}
public static int ByZDIgnoreCase(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}
Arrays.sort(names, (o1, o2) -> StringOrder.ByLength(o1, o2));
Arrays.sort(names, StringOrder::ByLength);
Arrays.sort(names, StringOrder::ByZD);
Arrays.sort(names, StringOrder::ByZDIgnoreCase);