使用Comparator实现自定义多维度排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liubin5620/article/details/82141990
package com.liu.basic;

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

/**
 * copyright (c) 2018, 刘 斌 All rights reserved 
 * 文件名称:SortTest.java 
 * 摘要:集合之自定义多维度排序 
 * 作 者:liu bin 
 * 创建时间:2018 年 08 月 28 日 
 * 版 本:1.0
 */
public class SortTest {

	public static void main(String[] args) {

		SortTest sortTest = new SortTest();

		List<User> userList = sortTest.getUserList();

		sortTest.sortFinalList(userList);

		for (int i = 0; i < userList.size(); i++) {
			System.out.println(userList.get(i));
		}
	}

	/**
	 * 获取UserList,对集合中的user对象进行排序.
	 * 
	 * @return
	 */
	public List<User> getUserList() {
		List<User> userList = new ArrayList<User>();
		User user1 = new User(12, 2, "张三");
		User user2 = new User(12, 1, "李四");
		User user3 = new User(15, 3, "王五");
		User user4 = new User(11, 4, "赵六");

		userList.add(user1);
		userList.add(user2);
		userList.add(user3);
		userList.add(user4);

		return userList;
	}

	/**
	 * 自定义排序:分数由低到高,升序排列,分数相同的情况下,按照userId升序排列,比如:
	 * (12,1,李四)-->(12,2,张三)-->(15,3,王五)
	 * 
	 * @param finalList 待排序对象的集合
	 */
	public void sortFinalList(List<User> finalList) {
		if (finalList != null) {
			Collections.sort(finalList, new Comparator<User>() {
				@Override
				public int compare(User o1, User o2) {
					if (o1.getScore() < o2.getScore()) {
						return -1;
					} else if (o1.getScore() > o2.getScore()) {// 左边大于右边,即后面的分数大于前面,按照分数升序排列
						return 1;
					} else { // 在分数相同的情况下
						if (o1.getUserId() < o2.getUserId()) {
							return -1;
						} else if (o1.getUserId() > o2.getUserId()) {// 按照学号升序排列
							return 1;
						} else {
							return 0;
						}
					}
				}
			});
		}
	}

	// user对象
	class User {

		public int score;
		public int userId;
		public String userName;

		public User() {

		}

		public User(int score, int userId, String userName) {
			super();
			this.score = score;
			this.userId = userId;
			this.userName = userName;
		}

		public int getScore() {
			return score;
		}

		public void setScore(int score) {
			this.score = score;
		}

		public int getUserId() {
			return userId;
		}

		public void setUserId(int userId) {
			this.userId = userId;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		@Override
		public String toString() {
			return "User [score=" + score + ", userId=" + userId + ", userName=" + userName + "]";
		}
	}

}
输出结果如下:

User [score=11, userId=4, userName=赵六]
User [score=12, userId=1, userName=李四]
User [score=12, userId=2, userName=张三]
User [score=15, userId=3, userName=王五]

猜你喜欢

转载自blog.csdn.net/liubin5620/article/details/82141990