1.二维数组按照列排序:
import java.util.Arrays;
import java.util.Comparator;
/**
* 二维数组排序示例
* @author YY2924 2014/11/28
* @version 1.0
*/
public class leetcode {
public static void main(String[] args) {
//二维数组
Integer[][] matrix = new Integer[][] {
{8,7},{9,5},{6,4}
};
//排序
Arrays.sort(matrix,new Comparator<Integer[]>() {
@Override
public int compare(Integer[] x, Integer[] y) {
if(x[1] < y[1]){ //x[1] < y[1]中1代表列,按照第2列排序. 降序排列
//return x[1] - y[1];升序排列 反则反之
return 1; // if(x[1] < y[1]) return 1与return y[1] - x[1];含义相同 代表降序排列
} else if(x[1] > y[1]){
return -1;
} else {
return 0;
}
}
});
//打印
for(Integer[] integers : matrix){
System.out.println(Arrays.toString(integers));
}
}
}
效果图:
2.比较对象:
import java.util.Comparator;
class StudentComparator implements Comparator<Student>{ //方法抽出来 重写
public int compare(Student o1, Student o2) {
//当然可以用其他成员变量来作为衡量比较的标准
return o1.getid().compareTo(o2.getid()); //比较列属性为String时,使用conmpareTo函数。 第一个字母相同,比较后续字母
}
}
class Student{
String id;
String name;
int age;
public Student(String id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public int getage(){
return age;
}
public String getname(){
return name;
}
public String getid(){
return id;
}
}
public class leetcode {
public static void main(String[] args) {
Student sc = new Student("10000", "lxz", 18);
Student sc1 = new Student("10001", "lx", 18);
Student sc2 = new Student("10003", "zh", 18);
Student sc3 = new Student("10002", "gd", 18);
Student scs[] = new Student[]{sc,sc1,sc2,sc3};
Arrays.sort(scs, new StudentComparator());//这里传出了一个比较器
for (int i = 0; i < scs.length; i++) {
System.out.println(scs[i].getname()+","+scs[i].getid()+","+scs[i].getage());
}
}
}
按照学生ID排列效果图:
按照学生名字排序: