import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MultiCompare implements Comparator {
int sort = 1;// sort 1正序 -1 倒序 filed 多字段排序
String[] filed;
public MultiCompare(int sort, String... filed) {
this.sort = sort == -1 ? -1 : 1;
this.filed = filed;
}
@Override
public int compare(Object o1, Object o2) {
int result = 0;
for (String file : filed) {
Object value1 = invokeMethod(file, o1);
Object value2 = invokeMethod(file, o2);
if (value1 == null || value2 == null) {
continue;
}
if (!(value1 instanceof Integer)
|| !(value2 instanceof Integer)) {
continue;
}
int v1 = Integer.valueOf(value1.toString());
int v2 = Integer.valueOf(value2.toString());
if (v1 == v2)
continue;
if (sort == 1) {
return v1 - v2;
} else if (sort == -1) {
return v2 - v1;
} else {
continue;
}
}
return result;
}
static Object invokeMethod(String propertiesName, Object object) {
try {
if (object == null)
return null;
if (!propertiesName.contains(".")) {
String methodName = "get" + getMethodName(propertiesName);
Method method = object.getClass().getMethod(methodName);
return method.invoke(object);
}
String methodName = "get"
+ getMethodName(propertiesName.substring(0,
propertiesName.indexOf(".")));
Method method = object.getClass().getMethod(methodName);
return invokeMethod(
propertiesName.substring(propertiesName.indexOf(".") + 1),
method.invoke(object));
} catch (Exception e) {
return null;
}
}
private static String getMethodName(String fildeName) {
byte[] items = fildeName.getBytes();
items[0] = (byte) ((char) items[0] - 'a' + 'A');
return new String(items);
}
public static void main(String args[]) {
LabelAlbum label1 = new LabelAlbum();
label1.setLabelId(1);
label1.setSequnces(1);
LabelAlbum label2 = new LabelAlbum();
label2.setLabelId(1);
label2.setSequnces(2);
LabelAlbum label3 = new LabelAlbum();
label3.setLabelId(3);
label3.setSequnces(4);
LabelAlbum label4 = new LabelAlbum();
label4.setLabelId(3);
label4.setSequnces(3);
LabelAlbum label5 = new LabelAlbum();
label5.setLabelId(4);
label5.setSequnces(2);
List<LabelAlbum> list = new ArrayList<LabelAlbum>();
list.add(label1);
list.add(label2);
list.add(label3);
list.add(label4);
list.add(label5);
Collections.sort(list,
new MultiCompare(1, "labelId", "sequnces"));
for (int i = 0; i < list.size(); i++) {
LabelAlbum labelAlbum = list.get(i);
System.out.println("labelId:" + labelAlbum.getLabelId()
+ " sequence:" + labelAlbum.getSequnces());
}
}
}
class LabelAlbum {
private int labelId;
private int sequnces;
public int getLabelId() {
return labelId;
}
public void setLabelId(int labelId) {
this.labelId = labelId;
}
public int getSequnces() {
return sequnces;
}
public void setSequnces(int sequence) {
this.sequnces = sequence;
}
}
java对list里面的对象进行多字段排序(借鉴整理)
最新推荐文章于 2024-04-26 17:19:16 发布