java collection.sort() 根據物件的某個屬性對list進行排序
阿新 • • 發佈:2019-01-06
1基本型別的list排序
/** * 對List物件按照某個成員變數進行排序 * @param list List物件 * @param sortField 排序的屬性名稱 * @param sortMode 排序方式:ASC,DESC 任選其一 */ public static <T> void sortList(List<T> list, final String sortField, final String sortMode) { if(list == null || list.size() < 2) { return; } Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { try { Class clazz = o1.getClass(); Field field = clazz.getDeclaredField(sortField); //獲取成員變數 field.setAccessible(true); //設定成可訪問狀態 String typeName = field.getType().getName().toLowerCase(); //轉換成小寫 Object v1 = field.get(o1); //獲取field的值 Object v2 = field.get(o2); //獲取field的值 boolean ASC_order = (sortMode == null || "ASC".equalsIgnoreCase(sortMode)); //判斷欄位資料型別,並比較大小 if(typeName.endsWith("string")) { String value1 = v1.toString(); String value2 = v2.toString(); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("short")) { Short value1 = Short.parseShort(v1.toString()); Short value2 = Short.parseShort(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("byte")) { Byte value1 = Byte.parseByte(v1.toString()); Byte value2 = Byte.parseByte(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("char")) { Integer value1 = (int)(v1.toString().charAt(0)); Integer value2 = (int)(v2.toString().charAt(0)); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("int") || typeName.endsWith("integer")) { Integer value1 = Integer.parseInt(v1.toString()); Integer value2 = Integer.parseInt(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("long")) { Long value1 = Long.parseLong(v1.toString()); Long value2 = Long.parseLong(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("float")) { Float value1 = Float.parseFloat(v1.toString()); Float value2 = Float.parseFloat(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("double")) { Double value1 = Double.parseDouble(v1.toString()); Double value2 = Double.parseDouble(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("boolean")) { Boolean value1 = Boolean.parseBoolean(v1.toString()); Boolean value2 = Boolean.parseBoolean(v2.toString()); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("date")) { Date value1 = (Date)(v1); Date value2 = (Date)(v2); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else if(typeName.endsWith("timestamp")) { Timestamp value1 = (Timestamp)(v1); Timestamp value2 = (Timestamp)(v2); return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1); } else { //呼叫物件的compareTo()方法比較大小 Method method = field.getType().getDeclaredMethod("compareTo", new Class[]{field.getType()}); method.setAccessible(true); //設定可訪問許可權 int result = (Integer)method.invoke(v1, new Object[]{v2}); return ASC_order ? result : result*(-1); } } catch (Exception e) { String err = e.getLocalizedMessage(); System.out.println(err); e.printStackTrace(); } return 0; //未知型別,無法比較大小 } }); }
2 對自定義物件進行排序
定義物件的程式碼如下
public class MailSchedule implements Comparable { private String mTitile; private Long mLongTime; private String mTime; private String mAddress; private boolean mIsFinish; public MailSchedule(Long time, String title, String address, boolean isfinish) { this.mLongTime = time; this.mTitile = title; this.mAddress = address; this.mIsFinish = isfinish; } private void getTime(Long time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); String day = sdf.format(new Date(time)); String date = day.split(" ")[0]; String mScheduletime = day.split(" ")[1]; this.mTime = mScheduletime; } public Long getLongTime() { return mLongTime; } public String getMailScheduleContent() { getTime(mLongTime); return mTime + " " + mTitile + " " + mAddress; } public void setIsFinish(boolean isFinish) { this.mIsFinish = isFinish; } public boolean getIsFinish() { return mIsFinish; } public boolean equals(Object obj) { if (this == obj) {//如果是引用同一個例項 return true; } if (obj != null && obj instanceof MailSchedule) { MailSchedule schedule = (MailSchedule) obj; return this.mLongTime == schedule.mLongTime && this.mTitile.equals(schedule.mTitile) && this.mAddress.equals(schedule.mAddress); } else { return false; } } @Override public int compareTo(Object comparestu) { long compareLongTime = ((MailSchedule) comparestu).mLongTime; return this.mLongTime.compareTo(compareLongTime); } }
方法一:物件實現 comparable介面,並實現其compareto方法,通過Collections.sort(currentDayContentList)對裝有該物件的list排序
for(int i= 0;i<n:i++) { MailSchedule mailSchedule = new MailSchedule(eventstarttime, eventTitle, eventLocation, false); if (!currentDayContentList.contains(mailSchedule)) { currentDayContentList.add(mailSchedule); } } Collections.sort(currentDayContentList);
方法二:定義一個比較器comparator,通過Collections.sort(currentDayContentList,new comparator())對其list 進行比較
Collections.sort(currentDayContentList, new Comparator<MailSchedule>() {
@Override
public int compare(MailSchedule lhs, MailSchedule rhs) {
return lhs.getLongTime().compareTo(rhs.getLongTime());
}
});
3 Arraylist 中contains方法 如下是原始碼
/**
* Searches this {@code ArrayList} for the specified object.
*
* @param object
* the object to search for.
* @return {@code true} if {@code object} is an element of this
* {@code ArrayList}, {@code false} otherwise
*/
@Override public boolean contains(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
return true;
}
}
} else {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
return true;
}
}
}
return false;
}
從原始碼中可以發現,會呼叫呼叫所比較物件的equals方法,來判斷是否為一個物件的例項!現在要對MailSchedule物件進行比較,可以重寫equals方法!
如果我們不在MailSchedule類中重寫equals()方法的話,雖然我們用contains方法進行了判斷,得到的連結串列的size仍舊是所new物件的個數,因為我們用new關鍵字建立MailSchedule物件,雖然它們的內容相同,但是JVM虛擬機器在堆中開闢了不同儲存空間,分別指向不同物件的引用。
需要我們根據MailSchedule的某個屬性進行判斷,是否為同一個人,我們需要重寫equals方法!程式碼如上面MailSchedule類中的equals方法