List 사용자 정의 정렬을 통해 Collections.sort 정렬 지원 대상 속성
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
public class ListComparator implements Comparator {
public ListComparator() {}
public ListComparator(String methodName) {
this.methodName = methodName;
}
// : : methodName
String methodName;
public Object getValue(Object bean, String methodName) throws Exception {
Method getMethod = bean.getClass().getMethod(methodName, null);
return getMethod.invoke(bean, null);
}
public int compare(Object obj1, Object obj2) {
int val = -1;
try {
if ( methodName == null ) {
val = _compare(obj1, obj2);
} else {
val = _compare(getValue(obj1, methodName), getValue(obj2, methodName));
}
} catch (Exception ex) {ex.printStackTrace();}
return val;
}
public int _compare(Object obj1, Object obj2) throws Exception {
if ( obj1 == null || obj2 == null ) return obj1 == null ? -1 : 1;
Class cl = obj1.getClass();
if ( obj1 instanceof java.lang.Comparable ) {
//byte int long float..number, date , boolean , char
Method getMethod = obj1.getClass().getMethod("compareTo", new Class[]{cl});
return (Integer) getMethod.invoke(obj1, new Object[]{obj2});
}
return -1;
}
}
//
class Test {
Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public static void main(String[] args) {
//
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
List list = new ArrayList();
for (long i = 0; i < 5; i++) {
list.add( new Date(System.currentTimeMillis() + (int) (Math.random() * 1000000000)) );
}
ListComparator c = new ListComparator();
Collections.sort(list, c);
for (int i = 0; i < list.size(); i++) {
System.out.println(simpleDateFormat.format(list.get(i)));
}
//
List<Test> userList = new ArrayList();
Test test = new Test();
test.setId(null);
userList.add(test);
for (long i = 0; i < 5; i++) {
test = new Test();
test.setId(i);
userList.add(test);
}
c = new ListComparator("getId");
Collections.sort(userList,Collections.reverseOrder(c));
for (int i = 0; i < userList.size(); i++) {
System.out.println(userList.get(i).getId());
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Exception Class에서 에러 코드 해석 ~초기초편~직장에서 C# 프로젝트가 내뿜는 오류 코드를 구문 분석하고 오류의 위치를 확인하기 위해 Exception class를 활용할 수 있었습니다. 지금까지 Exception Class 에 대해서 별로 파악할 수 없었기 때...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.