作者:面向對象
近日工作當中需要將一些數據按一定的格式進行排序,而這些數據是從數據庫當中查詢出來的一些對象的某個屬性,無法按此屬性進行排序查詢。爲此想到將對象取出後再將對其按某格式進行排序,這就需要運用到對集合進行排序。經高人指點,發現以下方法比較好用,特記下一筆。
- /**
- * 根據分類得到與分類相關的所有品牌信息
- */
- 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);
- }
- }
/** * 根據分類得到與分類相關的所有品牌信息 */ 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當中已定義好了的字符比較方法。如果我們有自己的特別需要,則需要自己重寫此方法。
關鍵的代碼: