怎么对list里面的数据的某一个字段进行排序

集合类List存放的数据,默认是按照放入顺序排序的。我们也可以对list中某一个元素进行排序。例如:

package test.tool.gui.dbtool.util;   
import java.util.ArrayList;   
import java.util.Collections;   
import java.util.Comparator;   
import java.util.List;   
public class Test {   
 public static void main(String[] args) {   
List list = new ArrayList();   
 //创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中   
        Student s1 = new Student();   
        s1.setAge(20);   
        Student s2 = new Student();   
        s2.setAge(19);   
        Student s3 = new Student();   
        s3.setAge(21);   
        list.add(s1);   
        list.add(s2);   
        list.add(s3);   
        System.out.println("排序前:"+list);   
        Collections.sort(list, new Comparator(){   
            public int compare(Student o1, Student o2) {   
                //按照学生的年龄进行升序排列   
                if(o1.getAge() > o2.getAge()){   
                    return 1;   
                }   
                if(o1.getAge() == o2.getAge()){   
                    return 0;   
               }   
               return -1;   
            }   
        });    
        System.out.println("排序后:"+list);   
    }   
}   

class Student{    
    private int age;   
    public int getAge() {   
        return age;   
    }   
    public void setAge(int age) {   
        this.age = age;   
    }   
    @Override  
    public String toString() {   
        return getAge()+"";   
    }   
}  

或者:写一个对list进行特定字段排序的方法

public List staytimeSort(List list){
		VisitDataDomain temp = null;  
        boolean exchange = false;  
        for (int i = 0; i < list.size(); i++) {  
            exchange = false;  
            for (int j = list.size() - 2; j >= i; j--) {  
                if (((VisitDataDomain) list.get(j + 1)).getStaytime()<  
                        ((VisitDataDomain) list.get(j)).getStaytime()) { 
                    temp = (VisitDataDomain) list.get(j + 1);  
                    list.set(j + 1, (VisitDataDomain) list.get(j));  
                    list.set(j, temp);  
                    exchange = true;  
                }  
            }  
            if (!exchange)  
                break;  
        }  
	return list;
	}
Collections.sort(pvlist,new Comparator() {
			@Override
			public int compare(VisitDataDomain o1, VisitDataDomain o2) {
				if(o1.getPv()>o2.getPv()){
					return 1;
				}
				if(o1.getPv()>o2.getPv()){
					return 0;
				}
				return -1;
			}
		});


你可能感兴趣的:(JAVA)