Java之——利用Comparator接口对多个排序条件进行处理

转载自:http://blog.csdn.net/l1028386804/article/details/56513205 

膜拜大神···

一、需求

    假设现在有个如此的需求:需要对一个这样的雇员列表进行排序,排序规则如下:
    1、首先级别最高的排在前面,
    2、如果级别相等,那么按工资排序,工资高的排在前面,
    3、如果工资相当则按入职年数排序,入职时间最长的排在前面。

雇员对象包含级别、工资和入职年份,代码如下:

[java]  view plain  copy
  1. package com.lyz.sort.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5.   
  6. /** 
  7.  * 雇员信息 
  8.  * @author liuyazhuang 
  9.  * 
  10.  */  
  11. public class Employee implements Serializable {  
  12.   
  13.     private static final long serialVersionUID = 4775629632953317597L;  
  14.       /** 
  15.      * ID 
  16.      */  
  17.     public int id;  
  18.     /** 
  19.      * 级别 
  20.      */  
  21.     public int level;  
  22.     /** 
  23.      * 工资 
  24.      */  
  25.     public int salary;  
  26.     /** 
  27.      * 入职年数 
  28.      */  
  29.     public int year;  
  30.   
  31.     public int getId() {  
  32.         return id;  
  33.     }  
  34.   
  35.     public void setId(int id) {  
  36.         this.id = id;  
  37.     }  
  38.   
  39.     public int getLevel() {  
  40.         return level;  
  41.     }  
  42.   
  43.     public void setLevel(int level) {  
  44.         this.level = level;  
  45.     }  
  46.   
  47.     public int getSalary() {  
  48.         return salary;  
  49.     }  
  50.   
  51.     public void setSalary(int salary) {  
  52.         this.salary = salary;  
  53.     }  
  54.   
  55.     public int getYear() {  
  56.         return year;  
  57.     }  
  58.   
  59.     public void setYear(int year) {  
  60.         this.year = year;  
  61.     }  
  62.   
  63.     public Employee(int id, int level, int salary, int year) {  
  64.         this.id = id;  
  65.         this.level = level;  
  66.         this.salary = salary;  
  67.         this.year = year;  
  68.     }  
  69. }  

二、实现Comparator接口

这里我们实现Java.util.Comparator接口,用于对雇员列表进行排序,代码如下:

[java]  view plain  copy
  1. package com.lyz.sort;  
  2.   
  3. import java.util.Comparator;  
  4.   
  5. import com.lyz.sort.bean.Employee;  
  6.   
  7. /** 
  8.  * 核心排序类 
  9.  * @author liuyazhuang 
  10.  * 
  11.  */  
  12. public class EmpComparator implements Comparator<Employee> {  
  13.   
  14.     @Override  
  15.     public int compare(Employee employee1, Employee employee2) {  
  16.           int cr = 0;  
  17.           //按级别降序排列  
  18.           int a = employee2.getLevel() - employee1.getLevel();  
  19.           if (a != 0) {  
  20.               cr = (a > 0) ? 3 : -1;  
  21.           } else {  
  22.               //按薪水降序排列  
  23.               a = employee2.getSalary() - employee1.getSalary();  
  24.               if (a != 0) {  
  25.                   cr = (a > 0) ? 2 : -2;  
  26.               } else {  
  27.                   //按入职年数降序排列  
  28.                   a = employee2.getYear() - employee1.getYear();  
  29.                   if (a != 0) {  
  30.                       cr = (a > 0) ? 1 : -3;  
  31.                   }  
  32.               }  
  33.           }  
  34.           return cr;  
  35.     }  
  36.   
  37. }  

三、验证排序结果

下面用一个单元测试,来验证排序结果是否正确

[java]  view plain  copy
  1. package com.lyz.sort.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collections;  
  5. import java.util.List;  
  6.   
  7. import org.junit.Test;  
  8.   
  9. import com.lyz.sort.EmpComparator;  
  10. import com.lyz.sort.bean.Employee;  
  11.   
  12. /** 
  13.  * 测试排序类 
  14.  *  
  15.  * @author liuyazhuang 
  16.  * 
  17.  */  
  18. public class SortTest {  
  19.     @Test  
  20.     public void sortTest() throws Exception {  
  21.         List<Employee> employeeList = new ArrayList<Employee>() {  
  22.             {  
  23.                 add(new Employee(191000010));  
  24.                 add(new Employee(29120007));  
  25.                 add(new Employee(351000012));  
  26.                 add(new Employee(45100006));  
  27.                 add(new Employee(5350003));  
  28.                 add(new Employee(6125001));  
  29.                 add(new Employee(75800010));  
  30.                 add(new Employee(8380002));  
  31.                 add(new Employee(9130005));  
  32.                 add(new Employee(10125004));  
  33.                 add(new Employee(11220004));  
  34.             }  
  35.         };  
  36.         Collections.sort(employeeList, new EmpComparator());  
  37.         System.out.println("ID\tLevel\tSalary\tYears");  
  38.         System.out.println("=============================");  
  39.         for (Employee employee : employeeList) {  
  40.             System.out.printf("%d\t%d\t%d\t%d\n", employee.getId(), employee.getLevel(), employee.getSalary(),  
  41.                     employee.getYear());  
  42.         }  
  43.         System.out.println("=============================");  
  44.     }  
  45. }  
运行结果:

四、附录

java.util.Comparator接口源代码

[java]  view plain  copy
  1. /* 
  2.  *  Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  *  contributor license agreements.  See the NOTICE file distributed with 
  4.  *  this work for additional information regarding copyright ownership. 
  5.  *  The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  *  (the "License"); you may not use this file except in compliance with 
  7.  *  the License.  You may obtain a copy of the License at 
  8.  * 
  9.  *     http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  *  Unless required by applicable law or agreed to in writing, software 
  12.  *  distributed under the License is distributed on an "AS IS" BASIS, 
  13.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  *  See the License for the specific language governing permissions and 
  15.  *  limitations under the License. 
  16.  */  
  17.   
  18. package java.util;  
  19.   
  20. /** 
  21.  * A {@code Comparator} is used to compare two objects to determine their ordering with 
  22.  * respect to each other. On a given {@code Collection}, a {@code Comparator} can be used to 
  23.  * obtain a sorted {@code Collection} which is <i>totally ordered</i>. For a {@code Comparator} 
  24.  * to be <i>consistent with equals</i>, its {code #compare(Object, Object)} 
  25.  * method has to return zero for each pair of elements (a,b) where a.equals(b) 
  26.  * holds true. It is recommended that a {@code Comparator} implements 
  27.  * {@link java.io.Serializable}. 
  28.  * 
  29.  * @since 1.2 
  30.  */  
  31. public interface Comparator<T> {  
  32.     /** 
  33.      * Compares the two specified objects to determine their relative ordering. The ordering 
  34.      * implied by the return value of this method for all possible pairs of 
  35.      * {@code (lhs, rhs)} should form an <i>equivalence relation</i>. 
  36.      * This means that 
  37.      * <ul> 
  38.      * <li>{@code compare(a,a)} returns zero for all {@code a}</li> 
  39.      * <li>the sign of {@code compare(a,b)} must be the opposite of the sign of {@code 
  40.      * compare(b,a)} for all pairs of (a,b)</li> 
  41.      * <li>From {@code compare(a,b) > 0} and {@code compare(b,c) > 0} it must 
  42.      * follow {@code compare(a,c) > 0} for all possible combinations of {@code 
  43.      * (a,b,c)}</li> 
  44.      * </ul> 
  45.      * 
  46.      * @param lhs 
  47.      *            an {@code Object}. 
  48.      * @param rhs 
  49.      *            a second {@code Object} to compare with {@code lhs}. 
  50.      * @return an integer < 0 if {@code lhs} is less than {@code rhs}, 0 if they are 
  51.      *         equal, and > 0 if {@code lhs} is greater than {@code rhs}. 
  52.      * @throws ClassCastException 
  53.      *                if objects are not of the correct type. 
  54.      */  
  55.     public int compare(T lhs, T rhs);  
  56.   
  57.     /** 
  58.      * Compares this {@code Comparator} with the specified {@code Object} and indicates whether they 
  59.      * are equal. In order to be equal, {@code object} must represent the same object 
  60.      * as this instance using a class-specific comparison. 
  61.      * <p> 
  62.      * A {@code Comparator} never needs to override this method, but may choose so for 
  63.      * performance reasons. 
  64.      * 
  65.      * @param object 
  66.      *            the {@code Object} to compare with this comparator. 
  67.      * @return boolean {@code true} if specified {@code Object} is the same as this 
  68.      *         {@code Object}, and {@code false} otherwise. 
  69.      * @see Object#hashCode 
  70.      * @see Object#equals 
  71.      */  
  72.     public boolean equals(Object object);  
  73. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值