最代码广告位
最代码官方的gravatar头像
最代码官方2014-08-08 16:06:54

java ArrayList数据对象按排序值大小倒叙排序

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

/**
 * 
 * @author www.zuidaima.com
 *
 */
public class ListSort {

	public static void main(String[] args) {
		List<User> users = new ArrayList<User>();
		int id = 0;
		User user = null;

		Random random = new Random();

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		id = random.nextInt(100000);
		user = new User(id);
		user.setId(id);
		users.add(user);

		System.out.println("Before sort:");
		for (User _user : users) {
			System.out.print(_user + " ");
		}

		Collections.sort(users, new Comparator<User>() {
			@Override
			public int compare(User user1, User user2) {
				Integer id1 = user1.getId();
				Integer id2 = user2.getId();
                                  //可以按User对象的其他属性排序,只要属性支持compareTo方法
				return id2.compareTo(id1);
			}
		});
		System.out.println("\nAfter sort 从大到小倒序:");
		for (User _user : users) {
			System.out.print(_user + " ");
		}
		
		Collections.sort(users, new Comparator<User>() {
			@Override
			public int compare(User user1, User user2) {
				Integer id1 = user1.getId();
				Integer id2 = user2.getId();
                                //可以按User对象的其他属性排序,只要属性支持compareTo方法
				return id1.compareTo(id2);
			}
		});
		System.out.println("\nAfter sort 从小到大正序:");
		for (User _user : users) {
			System.out.print(_user + " ");
		}
	}

}

class User {
	private int id;

	public User(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return id + "";
	}
}

程序运行输出结果:

Before sort:
49459 73363 18294 65350 36522 77535 38273 58512 34980 
After sort 倒序:
77535 73363 65350 58512 49459 38273 36522 34980 18294 
After sort 正序:
18294 34980 36522 38273 49459 58512 65350 73363 77535 


打赏

顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友