代码:
import java.util.ArrayList; import java.util.Comparator; import java.util.List; class Emp{ String name; int age; public Emp(String name,int age) { this.name=name; this.age=age; } public String toString() { return "Emp name="+name+" age="+age; } } public class Dept { private List<Emp> emps; public Dept() { emps=new ArrayList<Emp>(); emps.add(new Emp("Bill",32)); emps.add(new Emp("Cindy",42)); emps.add(new Emp("Cindy",12)); emps.add(new Emp("Cindy",52)); emps.add(new Emp("Douglas",92)); emps.add(new Emp("Andy",22)); } public void printEmps() { for(Emp emp:emps) { System.out.println(emp); } } /** * Sort by age */ public void sort1() { emps.sort(new Comparator<Emp>() { public int compare(Emp a1, Emp a2){ return a1.age-a2.age; } }); } /** * Sort by name */ public void sort2() { emps.sort((Emp a1, Emp a2)->a1.name.compareTo(a2.name)); } /** * Sort by name,if same name,sort by age */ public void sort3() { emps.sort(new Comparator<Emp>() { public int compare(Emp a1, Emp a2){ int result=a1.name.compareTo(a2.name); if(result==0) { return a1.age-a2.age; }else { return result; } } }); } public static void main(String[] args) { Dept dept=new Dept(); dept.sort1(); dept.printEmps(); System.out.println("--------------"); dept.sort2(); dept.printEmps(); System.out.println("--------------"); dept.sort3(); dept.printEmps(); } }
输出:
Emp name=Cindy age=12 Emp name=Andy age=22 Emp name=Bill age=32 Emp name=Cindy age=42 Emp name=Cindy age=52 Emp name=Douglas age=92 -------------- Emp name=Andy age=22 Emp name=Bill age=32 Emp name=Cindy age=12 Emp name=Cindy age=42 Emp name=Cindy age=52 Emp name=Douglas age=92 -------------- Emp name=Andy age=22 Emp name=Bill age=32 Emp name=Cindy age=12 Emp name=Cindy age=42 Emp name=Cindy age=52 Emp name=Douglas age=92
--END-- 2019.11.06