在Java中對集合當中的物件進行排序

hyeveryone發表於2011-11-18
轉載自:http://amcucn.iteye.com/blog/270697 

作者:物件導向

近日工作當中需要將一些資料按一定的格式進行排序,而這些資料是從資料庫當中查詢出來的一些物件的某個屬性,無法按此屬性進行排序查詢。為此想到將物件取出後再將對其按某格式進行排序,這就需要運用到對集合進行排序。經高人指點,發現以下方法比較好用,特記下一筆。

 

Java程式碼 複製程式碼 收藏程式碼
  1. /**  
  2.      * 根據分類得到與分類相關的所有品牌資訊  
  3.      */  
  4.     private Collection getBrandByType(Integer typeId) {   
  5.         String hql = "select distinct pt.box.productInfo.brand From ProductTop As pt where pt.box.productInfo.type.id=" + typeId ;   
  6.         List allBrandList = utilDao.executeQuery(hql);   
  7.         //對集合進行排序   
  8.         Collections.sort(allBrandList, new compareList() );   
  9.         return allBrandList;   
  10.     }   
  11.        
  12.     /**  
  13.      * 比較兩個物件的大小,實現Comparator介面  
  14.      */  
  15.     private class compareList implements Comparator{   
  16.         public int compare(Object o1, Object o2) {   
  17.             Catagory c1 = (Catagory)o1;   
  18.             Catagory c2 = (Catagory)o2;   
  19.             String catagoryName1 = c1.getName();   
  20.             String catagoryName2 = c2.getName();   
  21. //通過比較兩個字串物件來排序。此處可以根據自己的需要寫兩個物件的具體比較內容   
  22.         return catagoryName1.compareTo(catagoryName2);   
  23.         }   
  24.            
  25.     }  
/**	 * 根據分類得到與分類相關的所有品牌資訊	 */	private Collection getBrandByType(Integer typeId) {		String hql = "select distinct pt.box.productInfo.brand From ProductTop As pt where pt.box.productInfo.type.id=" + typeId ;		List allBrandList = utilDao.executeQuery(hql);		//對集合進行排序		Collections.sort(allBrandList, new compareList() );		return allBrandList;	}		/**	 * 比較兩個物件的大小,實現Comparator介面	 */	private class compareList implements Comparator{		public int compare(Object o1, Object o2) {			Catagory c1 = (Catagory)o1;			Catagory c2 = (Catagory)o2;			String catagoryName1 = c1.getName();			String catagoryName2 = c2.getName();//通過比較兩個字串物件來排序。此處可以根據自己的需要寫兩個物件的具體比較內容		return catagoryName1.compareTo(catagoryName2);		}			}

 

大致步驟如下:
首先通過一般的查詢得到一組物件集合此處為:allBrandList 。然後使用Collections.sort方法進行排序,在這個方法當中需要一個實現了Comparator介面的類用來比較兩個物件大小。
至於兩個物件的大小如何比較,是由自己來定義的,此處只使用了String類當中的compareTo方法,也就是Java當中已定義好了的字元比較方法。如果我們有自己的特別需要,則需要自己重寫此方法。
關鍵的程式碼:

Java程式碼 複製程式碼 收藏程式碼
  1. Collections.sort(allBrandList, new compareList());  

相關文章