题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
自定义类可以实现Comparable接口
import java.util.ArrayList; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Student.flag = in.nextInt(); ArrayList<Student> list = new ArrayList<>(); // 注意 hasNext 和 hasNextLine 的区别 while (n-- > 0) { // 注意 while 处理多个 case list.add(new Student(in.next(), in.nextInt())); } list.stream().sorted().forEach(System.out::println); } } class Student implements Comparable<Student> { String name; int score; static int flag; Student(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return String.format("%s %d", this.name, this.score); } @Override public int compareTo(Student o) { return flag == 1 ? this.score - o.score : o.score - this.score; } }