例如:实体类
public class Sign {
int keyIndex;
String name;
public Sign(int keyIndex, String name) {
super();
this.keyIndex = keyIndex;
this.name = name;
}
public int getKeyIndex() {
return keyIndex;
}
public void setKeyIndex(int keyIndex) {
this.keyIndex = keyIndex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Sign [keyIndex=" + keyIndex + ", name=" + name + "]";
}
}
假设有一个对该实体类的集合如下,调用如下的方法的会对该signResult 集合按对象中keyIndex字段的大小进行排序。
排序结果是该集合会按keyIndex的大小从小到大进行排序。
public static void testSort(){
ArrayList<Sign>signResult =new ArrayList<>();
signResult.add(new Sign(3, "test3"));
signResult.add(new Sign(1, "test2"));
signResult.add(new Sign(2, "test2"));
Collections.sort(signResult, new Comparator<Sign>() {
@Override
public int compare(Sign a, Sign b) {
if (a.getKeyIndex()< b.getKeyIndex()) {
return -1;
}
if (a.getKeyIndex() > b.getKeyIndex()) {
return 1;
}
return 0;
}
});
}