清华大学 成绩排序

import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by fhqplzj on 17-1-25 at 下午10:19.
 */
class Student {
    private int index;
    private String name;
    private int score;

    Student(int index, String name, int score) {
        this.index = index;
        this.name = name;
        this.score = score;
    }

    public int getIndex() {
        return index;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    @Override
    public String toString() {
        return String.format("%s %d", name, score);
    }
}

public class My1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            int n = scanner.nextInt();
            boolean ascending = scanner.nextInt() == 1;
            ArrayList students = new ArrayList<>(n);
            for (int i = 0; i < n; i++) {
                students.add(new Student(i, scanner.next(), scanner.nextInt()));
            }
            if (ascending) {
                students.sort((o1, o2) -> {
                    if (o1.getScore() != o2.getScore()) {
                        return o1.getScore() < o2.getScore() ? -1 : 1;
                    } else {
                        return Integer.compare(o1.getIndex(), o2.getIndex());
                    }
                });
            } else {
                students.sort((o1, o2) -> {
                    if (o1.getScore() != o2.getScore()) {
                        return o1.getScore() < o2.getScore() ? 1 : -1;
                    } else {
                        return Integer.compare(o1.getIndex(), o2.getIndex());
                    }
                });
            }
            students.forEach(System.out::println);
        }
    }
}

你可能感兴趣的:(清华大学 成绩排序)