最近用java抓取数据的时候,遇到了需要对拿到的List集合按照多个字段进行排序。首先得让排序的实体类实现Comparable类并且重写它的compareTo方法,在compareTo中你可以自定义排序的规则。如果前者大于后者,则返回1,若果相等则返回0,若果前者小于后者,则返回-1;String字符串比较的时候也会经常用到这个compareTo方法,查看String类,可以看到它也实现了Comparable类。
String类
新建一个User类:按照id升序,age降序来排序。
package com.entity;
public class User implements Comparable<User>{
private int id;
private int age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
@Override
public int compareTo(User o) {
// TODO Auto-generated method stub
if(this.getId()>o.getId())
{
return 1;
}else if(this.getId()<o.getId()){
return -1;
}else{
if(this.getAge()>o.getAge()){
return -1;
}else{
return 1;
}
}
}
}
再建一个Junit测试类
package com.test;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.Test;
import com.entity.User;
public class TestJunit {
@Test
public void test() {
User u1=new User(1, 1, "A");
User u2=new User(3, 2, "B");
User u3=new User(3, 3, "C");
User u4=new User(5, 4, "D");
User u5=new User(5, 5, "E");
ArrayList<User> list=new ArrayList<User>();
list.add(u2);
list.add(u5);
list.add(u3);
list.add(u4);
list.add(u1);
System.out.println("排序前:");
for(int i=0;i<list.size();i++)
{
System.out.println("id:"+list.get(i).getId() +" age:"+list.get(i).getAge() +" name:"+list.get(i).getName());
}
System.out.println("排序后:");
//id升序,age降序排序
Collections.sort(list);
for(int i=0;i<list.size();i++)
{
System.out.println("id:"+list.get(i).getId() +" age:"+list.get(i).getAge() +" name:"+list.get(i).getName());
}
System.out.println("");
}
}
排序结果
网友评论