题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*; public class Main { static int orderFlag; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); orderFlag = in.nextInt(); if (orderFlag == 0) orderFlag = -1; Set<Student> student = new TreeSet<>( new Comparator<Student>() { public int compare(Student s1, Student s2) { if (s1.getScore() != s2.getScore()) return orderFlag * (s1.getScore() - s2.getScore()); else return 1; // 保证插入自然序 } } ); for (int i = 0; i < n; i++) { String name = in.next(); int score = in.nextInt(); student.add(new Student(name, score)); } for (Student s : student) System.out.printf("%s %d\n", s.getName(), s.getScore()); } } // 封装对象,因为Map不便于对value做排序 class Student { private int score; private String name; Student(String name, int score) { this.name = new String(name); this.score = score; } public String getName() { return name; } public int getScore() { return score; } }