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

轉載自: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());  
發佈了9 篇原創文章 · 獲贊 2 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章