1. 程式人生 > >List使用Object的某個屬性進行排序(正序,倒序)

List使用Object的某個屬性進行排序(正序,倒序)

package com.test;

public class User {
	private String name;
	private Integer orderNo;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getOrderNo() {
		return orderNo;
	}
	public void setOrderNo(Integer orderNo) {
		this.orderNo = orderNo;
	}
	
}

對List<User>進行排序:

package com.test;

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) {
				User user1 =new User();
				user1.setName("c");
				user1.setOrderNo(3);
				User user2 =new User();
				
				user2.setName("c");
				user2.setOrderNo(1);
				User user3 =new User();
				user3.setName("b");
				user3.setOrderNo(2);
                List<User> list = new ArrayList<User>();
				list.add(user1);
				list.add(user2);
				list.add(user3);
				Collections.sort(list,new Comparator<User>(){
					public int compare(User arg0, User arg1){
						return arg1.getOrderNo().compareTo(arg0.getOrderNo());
					}
				});
				//倒序結果:
				/*c:3
				b:2
				c:1*/
				for(User u:list){
					System.out.println(u.getName()+":"+u.getOrderNo());
					
				}
				
				//正序結果
				/*c:1
				b:2
				c:3*/
				Collections.sort(list,new Comparator<User>(){
					public int compare(User arg0, User arg1){
						return arg0.getOrderNo().compareTo(arg1.getOrderNo());
					}
				});
				for(User u:list){
					System.out.println(u.getName()+":"+u.getOrderNo());
					
				}
	}

}