Arrays结合Comparator用法小结

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排列效果图:

按照学生名字排序:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值