引用类型排序API接口Comparable

import java.util.*;

/**
 * 成绩排序
 * @author Green.Gee
 * @date 2022/11/21 14:56
 * @email [email protected]
 */
public class ResultSort {

    public static int SORT_TYPE = 0;// 默认降序
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String n = in.nextLine();// 队列数
            int len = Integer.parseInt(n);
            String sortType = in.nextLine();// 0 降序  1 升序
            List<Stu> stus = new ArrayList<>();
            SORT_TYPE = Integer.valueOf(sortType);
            for(int i = 1; i <= len; i++){
                String [] line = in.nextLine().split(" ");
                Stu stu = new Stu(line[0],Integer.valueOf(line[1]));
                stus.add(stu);
            }
            Collections.sort(stus);
            stus.forEach(item ->{

                System.out.println(item.getName()+" "+item.getScore());

            });

        }
    }

    static class Stu implements  Comparable<Stu>{

        private static final Comparator<Stu> COMPARATOR =
                Comparator.comparingInt((Stu dc) -> dc.score);

        String name;
        int score;

        @Override
        public int compareTo(Stu o) {
            int c = Integer.compare(o.getScore(),score);
            if(SORT_TYPE == 1){
                return COMPARATOR.compare(this,o);

            }else{
               return COMPARATOR.compare(o,this);
            }
        }


        public Stu(String name,int score){
            this.name = name;
            this.score = score;
        }

        public Stu(){}

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getScore() {
            return score;
        }

        public void setScore(int score) {
            this.score = score;
        }

        @Override
        public String toString() {
            return "Stu{" +
                    "name='" + name + '\'' +
                    ", score=" + score +
                    '}';
        }
    }

}

你可能感兴趣的:(算法【,Hard,Code】,java)