比较器Comparator的使用

一:首先定义Employee实体类

package com.yhd.comparator;

/**
 * @author sunfei
 * @CreateTime 2016-8-10 下午05:01:14
 */
public class Employee {
    private Integer age;
    private Integer salary;
    private String name;

    public Employee(Integer age, Integer salary, String name) {
        super();
        this.age = age;
        this.salary = salary;
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

二:实现比较器

package com.yhd.comparator;

import java.util.Comparator;

/**
 * @author sunfei
 * @CreateTime 2016-8-10 下午05:04:39
 */
public class EmployeeComparator implements Comparator<Employee> {

    public int compare(Employee emp1, Employee emp2) {
        //按照薪水降序排序,薪水高的排在前面,薪水低的排在后面。用后者减去前者;
        int result = emp2.getSalary().compareTo(emp1.getSalary());
        if(result != 0){
            return result;
        }
        //薪水相同,按照年龄升序排序,年龄低的排在前面,年龄高的排在后面。用前者减去后者;
        if(emp1.getAge() != null && emp2.getAge()!=null) {
            result = emp1.getAge().compareTo(emp2.getAge());
        }
        if(result != 0){
            return result;
        }
        //年龄相同,按照姓名排序。字母小的排在前面,字母大的排在后面。用前者减去后者;
        if(emp1.getName()!=null && emp2.getName()!=null){
            result = emp1.getName().compareTo(emp2.getName());
        }
        return result;
    }

}

三:测试类

package com.yhd.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author sunfei
 * @CreateTime 2016-8-10 下午05:09:38
 */
public class TestComparator {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Employee> emps = new ArrayList<Employee>();
        emps.add(new Employee(23, 4000, "c"));
        emps.add(new Employee(12, 4000, "z"));
        emps.add(new Employee(12, 2000, "a"));
        
        Collections.sort(emps, new EmployeeComparator());
        for(Employee employee : emps) {
            System.out.println("年龄:"+employee.getAge()+"------"+"薪水:"+employee.getSalary()+"----"+"姓名:"+employee.getName());
        }
    }

}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值