题解

使用jdk8的新特性stream对数据进行,升序或降序排序。

代码

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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int sortType = sc.nextInt();
            List<Student> list = new ArrayList<>();
            while (n-- > 0) {
                String name = sc.next();
                int age = sc.nextInt();
                Student stu = new Student(name, age);
                list.add(stu);
            }

            List<Student> newList = list.stream() // 默认升序排序
                                    .sorted(Comparator.comparing(Student::getAge))
                                    .collect(Collectors.toList());
            if (0 == sortType) { // 降序排序
                newList = list.stream()
                          .sorted(Comparator.comparing(Student::getAge).reversed())
                          .collect(Collectors.toList());
            }

            for (int i = 0; i < newList.size(); i++) {
                Student stu = newList.get(i);
                System.out.println(stu.getName() + " " + stu.getAge());
            }
        }
    }
}

class Student {
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }
}