对list进行排序

我们在List里存入一些对象,比如person对象,若想要让这些对象按他们的age属性大小排序,不用我们自己实现,java已经帮我们实现了,我们只要实现Comparator接口,重写其中的compare方法就好。

<span style="font-size: small;">public class Person {  
    String name;  
    int age;  
      
    public Person(String name, int age){  
        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;  
    }  
      
}  
</span>  

  1. <span style="font-size: small;">import java.util.Comparator;  
  2.   
  3. public class MyComparetor implements Comparator {  
  4. //   按年龄排序  
  5. //  public int compare(Object o1, Object o2){  
  6. //       Person p1=(Person)o1;  
  7. //       Person p2=(Person)o2;  
  8. //       return (p2.getAge()-p1.getAge());  
  9. //      }  
  10.   
  11.   
  12. //  按姓名排序     
  13.     public int compare(Object o1, Object o2){  
  14.          Person p1=(Person)o1;  
  15.          Person p2=(Person)o2;  
  16.          return (p1.getName().compareTo(p2.getName()));  
  17.         }  
  18.       
  19. }</span>  

上面的compare方法会返回3种值, -1,0,1. 当第一个大于第二个的时候返回1,相等返回0,小于返回-1

按姓名排序中,用p1compareto p2是升序,反之是降序


测试类:

Java代码  收藏代码
  1. <span style="font-size: small;">public static void main(String[] args) {  
  2.         // TODO Auto-generated method stub  
  3.         List list=new ArrayList();  
  4.         list.add(new Person("weichao",22));  
  5.         list.add(new Person("lb",20));  
  6.         list.add(new Person("sf",18));  
  7.         list.add(new Person("wj",30));  
  8.         Collections.sort(list,new MyComparetor());  
  9.         Person person = null;  
  10.         for(int i = 0; i < list.size(); i++){  
  11.             person = (Person) list.get(i);  
  12.             System.out.println("name:" + person.getName() + ",age:" + person.getAge());  
  13.         }  
  14.     }</span>  

这是我找的方法,但是谁知道,有没有简单的方法对list进行排序?

原文地址:https://www.cnblogs.com/tanqianqian/p/5975016.html