java中的Collections.sort排序

來源:互聯網
上載者:User

 在java web開發中,我們有時會遇到這種情況:從資料庫中查詢出一串資料,把它們放入了LIST裡面 然後在前端頁面上顯示出來,現在我要在頁面上控制它們排序,比如一個下拉框,選擇了日期,把查出來的資料進行排序,對於這樣的排序要求,我們可以寫通用的排序方法。

具體代碼如下:

排序演算法:

//利用 Collections.sort排序

public void sort(List<E> list,final String method,final String sort){  
  Collections.sort(list,new Comparator(){
   public int compare(Object a,Object b){
    int ret = 0;
    try{
     Method m1 = ((E)a).getClass().getMethod(method, null);
     Method m2 = ((E)b).getClass().getMethod(method, null);
     if("desc".equals(sort)&&sort!=null){

     //因為這個方法是按照字串去排序的,所對針對於數字排序,思路為:將數字也當成字串,先去比較長度,若長度一樣,就比較字串大小

      ret = String.valueOf(m2.invoke(((E)b), null).toString().length()).compareTo(String.valueOf(m1.invoke(((E)a), null).toString().length()));
         if(m2.invoke(((E)b), null).toString().length()==m1.invoke(((E)a), null).toString().length()){
          ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());
         }
     }else{
      ret = String.valueOf((m1.invoke(((E)a), null).toString().length())).compareTo(String.valueOf(m2.invoke(((E)b), null).toString().length()));
     }
    }catch(NoSuchMethodException e){
     e.printStackTrace();
    } catch (IllegalArgumentException e) {
     e.printStackTrace();
    } catch (IllegalAccessException e) {
     e.printStackTrace();
    } catch (InvocationTargetException e) {
     e.printStackTrace();
    }
    return ret;
   }
  });
 }

在具本list中調用:

SortList<Communication> ls = new SortList<Communication>();
  ls.sort(list1, "getRatio", "desc");

其中:list1是從資料庫中所查詢出來的,getRatio指的是排序列的get方法,desc是指降序排列

 

註:其中對於技術開發而言,一些都是以減少工作量為目的,寫個通用的方法,將為今後的開發工作省了不少事!

大家有什麼問題的,可以留言!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.