直接上代码
1.测试类
public class ListSortTest {
public static void main(String[] args) {
List<Demo> list = new ArrayList<Demo>();
Demo demo = new Demo("1", "b23");
Demo demo2 = new Demo("1", "a23");
Demo demo3 = new Demo("1", "z23");
list.add(demo);
list.add(demo2);
list.add(demo3);
System.out.println("排序前----------------------");
for (Demo demo1 : list) {
System.out.println(demo1);
}
System.out.println("排序后----------------------");
Collections.sort(list);
for (Demo demo1 : list) {
System.out.println(demo1);
}
}
}
2.Demo实体类
public class Demo implements Comparable<Demo> {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Demo(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Demo o) {
if (this.name.compareTo(o.getName()) > 1) {
return 1;
} else if (this.name.compareTo(o.getName()) == 0) {
return 0;
}
return -1;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("id", id)
.append("name", name)
.toString();
}
}
输出打印结果::
排序前----------------------
test.Demo@3d82c5f3[id=1,name=b23]
test.Demo@2b05039f[id=1,name=a23]
test.Demo@61e717c2[id=1,name=z23]
排序后----------------------
test.Demo@2b05039f[id=1,name=a23]
test.Demo@3d82c5f3[id=1,name=b23]
test.Demo@61e717c2[id=1,name=z23]