实现Comparator 对List<?>进行排序

首选需要有个Entity类 ,里面有属性有方法

 1 package demo;
 2 
 3 public class Entity {
 4     private String empNo ; 
 5     private String empName ; 
 6     private float sal ; 
 7 
 8     public String getEmpNo() { 
 9     return empNo; 
10     } 
11     public void setEmpNo(String empNo) { 
12     this.empNo = empNo; 
13     } 
14     public String getEmpName() { 
15     return empName; 
16     } 
17     public void setEmpName(String empName) { 
18     this.empName = empName; 
19     } 
20     public float getSal() { 
21     return sal; 
22     } 
23     public void setSal(float sal) { 
24     this.sal = sal; 
25     } 
26 
27     public Entity(String empNo,String empName,float sal){ 
28     this.empNo = empNo ; 
29     this.empName = empName ; 
30     this.sal = sal ; 
31     } 
32     
33 }

现在我想对 empName 这个属性进行排序

此时需要MyComparator 实现Comparator<Object>

 1 package demo;
 2 
 3 import java.util.Comparator;
 4 
 5 public class MyComparator implements Comparator<Object>{ 
 6 
 7     public int compare(Object o1,Object o2) { 
 8         Entity s1 = (Entity) o1;
 9         Entity s2 = (Entity) o2;
10 //        return (int) (s1.getSal() - s2.getSal()); // 按Id排
11         return s1.getEmpName().compareTo(s2.getEmpName()); // 按姓名排
12     } 
13 } 

测试类如下

 1 package demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 
 6 public class test {
 7     public static void main(String[] args) {
 8          ArrayList<Entity> list = new ArrayList<Entity>();
 9         Entity e1 = new Entity(null, null, 0);
10         Entity e2 = new Entity(null, null, 0);
11         Entity e3 = new Entity(null, null, 0);
12         Entity e4 = new Entity(null, null, 0);
13         e1.setEmpName("TY2014000002");
14         String s1= e1.getEmpName();
15         s1 = s1.substring(6);
16         System.out.println(s1+"+++++++++");
17         e2.setEmpName("TY2016000009");
18         e3.setEmpName("TY2016000003");
19         e4.setEmpName("TY2014000001");
20         list.add(e1);
21         list.add(e2);
22         list.add(e3);
23         list.add(e4);
24         for(int i=0;i<list.size();i++){ 
25             Entity emp = (Entity)list.get(i) ; 
26             System.out.println(emp.getEmpName()); 
27         } 
28         System.out.println("-------------------");
29         MyComparator mc = new MyComparator() ; 
30         Collections.sort(list, mc) ; 
31         for(int i=0;i<list.size();i++){ 
32             Entity emp = (Entity)list.get(i) ; 
33             System.out.println(emp.getEmpName()); 
34         }  
35      }
36 }

原文地址:https://www.cnblogs.com/ScarecrowAnBird/p/7356498.html