java List 排序 Collections.sort

今天项目中用到了对list中的对象排序,把代码和大家分享下,用工具类collections中的sort方法排序。写一个比较类实现Comparator接口,具体两个类的大小就取决于实现这个接口时里边的逻辑。接下来大家看下例子

 

 

以下是比较类的实现

package org.sort;

import java.util.Comparator;


public class ComparatorPerson implements Comparator{
	public int compare(Object arg0, Object arg1) {
	        Person p0=(Person)arg0;
	        Person p1=(Person)arg1;
	        
			if(p0.getAge()<p1.getAge()){
				return 1;
			}else if(p0.getAge()==p1.getAge()){
			    if(p0.getName().compareTo(p1.getName())>0){
			        return 1; 
			    }else{
			        return 0;
			    }
			    
			}else{
				return 0;
			}
	}
}

 

 

以下是需要比较的类

package org.sort;

public class Person {
    private int age;
    private String name;
    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 Person(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
    
}

 

 

 

以下是测试类

 

package org.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(10, "张三"));
        list.add(new Person(10, "张三丰"));
        list.add(new Person(11, "张三"));
        list.add(new Person(11, "张三丰"));
        for (Person p : list) {
            System.out.println(p.getAge() + "--排序前---" + p.getName());
        }
        Collections.sort(list, new ComparatorPerson());
        for (Person p : list) {
            System.out.println(p.getAge() + "---排序后--" + p.getName());
        }
        String[] ss = "a||b  ".split("\\|\\|");
        System.out.println(ss.length);
        for (String string : ss) {
            System.out.println(string);
        }
    }
}

 

你可能感兴趣的:(list排序,Comparator.sort)