java多条件优先级排序 --------- Comparator

来源:互联网 发布:linux防火墙ip地址配置 编辑:程序博客网 时间:2024/06/06 21:39
Comparator用法代码 复制代码 收藏代码
  1. package com;   
  2.   
  3. import java.util.ArrayList;   
  4. import java.util.Collections;   
  5. import java.util.Comparator;   
  6. import java.util.List;   
  7.   
  8. public class ComparatorDemo {   
  9.     public List<Student> mList;   
  10.     public List<Comparator<Student>> mCmpList = new ArrayList<Comparator<Student>>();   
  11.     public ComparatorDemo(List<Student> list){   
  12.         mList = list;   
  13.         mCmpList.add(compareAgeASC);   
  14.         mCmpList.add(comparePointDESC);   
  15.         sort(mList, mCmpList);   
  16.     }   
  17.     public void sort(List<Student> list, final List<Comparator<Student>> comList) {   
  18.         if (comList == null)   
  19.             return;   
  20.         Comparator<Student> cmp = new Comparator<Student>() {   
  21.             @Override   
  22.             public int compare(Student o1, Student o2) {   
  23.                 for (Comparator<Student> comparator : comList) {   
  24.                     if (comparator.compare(o1, o2) > 0) {   
  25.                         return 1;   
  26.                     } else if (comparator.compare(o1, o2) < 0) {   
  27.                         return -1;   
  28.                     }   
  29.                 }   
  30.                 return 0;   
  31.             }   
  32.         };   
  33.         Collections.sort(list, cmp);   
  34.     }   
  35.   
  36.     private Comparator<Student> compareAgeASC = new Comparator<ComparatorDemo.Student>() {   
  37.   
  38.         @Override   
  39.         public int compare(Student o1, Student o2) {   
  40.             return o1.age > o2.age ? 1 : -1;   
  41.         }   
  42.     };   
  43.   
  44.     private Comparator<Student> comparePointDESC = new Comparator<ComparatorDemo.Student>() {   
  45.   
  46.         @Override   
  47.         public int compare(Student o1, Student o2) {   
  48.             return o1.point < o2.point ? 1 : -1;   
  49.         }   
  50.     };   
  51.   
  52.     /**   
  53.      * @author 80059130  
  54.      *    
  55.      */   
  56.     class Student {   
  57.         public int age;   
  58.         public String name;   
  59.         public int point;   
  60.     }   
  61. }  

  1、Comparator

  Collections.sort(List<T> list, Comparator<? super T> c) ;

  2、T实现了Comparable 接口

  Collections.sort(List<T> list);

原创粉丝点击