JAVA多字段排序

使用JDK1.8的stream api可以轻松实现多字段排序

首先创建Student类如下

/**
 * @title
 * @author gavin
 * @date 2020年8月11日
 */
public class Student {
	
	// 姓名
	private String name;
	// 分数
	private int score;
	// 名次
	private int rank;
	
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getRank() {
		return rank;
	}
	public void setRank(int rank) {
		this.rank = rank;
	}
}

然后创建StudentTest类对其进行排序测试

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StudentTest {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<Student>();
		
		Student s1 = new Student();
		s1.setName("张萌");
		s1.setScore(79);
		
		Student s2 = new Student();
		s2.setName("李四");
		s2.setScore(80);
		
		Student s3 = new Student();
		s3.setName("王五");
		s3.setScore(81);
		
		Student s4 = new Student();
		s4.setName("张三");
		s4.setScore(79);
		
		list.add(s1);
		list.add(s2);
		list.add(s3);
		list.add(s4);
		
		// 先按照分数降序,然后根据姓名拼音升序
		list = list.stream()
			.sorted(
					Comparator.comparing(Student::getScore).reversed()
						.thenComparing(Student::getName)
			).collect(Collectors.toList());
		for(Student student : list) {
			System.out.println(student.getName() + "," + student.getScore());
 		}
	}
}

运行程序,输出结果如下

王五,81
李四,80
张三,79
张萌,79

你可能感兴趣的:(Java,java多字段排序,java排序)