在排序的时候,给sort()方法传入一个比较器。传入一个实现比较器接口的匿名内部类,告诉sort()方法按照比较器来对list中的对象进行排序。如下所示:
public class Test
{
public static void main(String[] args)
{
ArrayList<Entity> list=new ArrayList<Entity>();
list.add(new Entity("余涛",24));
list.add(new Entity("王宁",13));
list.add(new Entity("崔同发",25));
System.out.println("排序前:"+list);
Collections.sort(list,new Comparator<Entity>() {
@Override
public int compare(Entity o1, Entity o2)
{
if(o1.getAge()>o2.getAge())
{
//返回1为o1放在后面
return 1;
}
else if(o1.getAge()<o2.getAge())
{
//返回-1为o1放在前面
return -1;
}
else
{
//返回0代表不排序,按之前的排序方法
return 0;
}
}
});
System.out.println("排序后:"+list);
}
}
class Entity
{
String name;
int age;
public Entity(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Entity [name=" + name + ", age=" + age + "]";
}
}
排序前:[Entity [name=余涛, age=24], Entity [name=王宁, age=13], Entity [name=崔同发, age=25]]
排序后:[Entity [name=王宁, age=13], Entity [name=余涛, age=24], Entity [name=崔同发, age=25]]
sort方法:
//返回1为o1放在后面 return 1; //返回-1为o1放在前面 return -1; //map对象转换为VO对象集合 //返回0代表不排序,按之前的排序方法 return 0;
业务场景:
//按是否含有分配任务(icedMemberManagementVO.getInvolveProject()字段是否为空)排序
Collections.sort(result, new Comparator<ICEDMemberVO>() {
@Override
public int compare(ICEDMemberVO o1, ICEDMemberVO o2) {
List<ICEDMemberManagementVO> icedMemberManagementVOS1 = o1.getIcedMemberManagementVOS();
List<ICEDMemberManagementVO> icedMemberManagementVOS2 = o2.getIcedMemberManagementVOS();
Integer a = 0;
Integer b = 0;
for (ICEDMemberManagementVO icedMemberManagementVO : icedMemberManagementVOS1){
if (StringUtils.isNotBlank(icedMemberManagementVO.getInvolveProject())){
a = 1;
}
}
for (ICEDMemberManagementVO icedMemberManagementVO : icedMemberManagementVOS2){
if (StringUtils.isNotBlank(icedMemberManagementVO.getInvolveProject())){
b = 1;
}
}
if (a == 0 && b == 0){
return 0;
}else if ( a == 1 && b == 1){
return 0;
}else if (a == 1){
return -1;
}else {
return -1;
}
}
});