为了账号安全,请及时绑定邮箱和手机立即绑定

如何在不使用可比较和比较器接口的情况下对地图进行排序?自定义排序怎么写?

如何在不使用可比较和比较器接口的情况下对地图进行排序?自定义排序怎么写?

浮云间 2022-12-21 10:52:40
问题- 我有一个学生班,它包含姓名、学号、三个科目分数 m1、m2、m3 和总分。如果两个或更多学生的分数相等,我需要根据他们的总分对学生对象进行排序,然后根据他们的姓名对其进行排序。注意- 我必须用谷歌搜索它,但在 stackoverflow 问题中没有得到预期的解决方案,每个问题都使用 Comparable 和 Comparator 接口。我创建了 Studnt 类public class Student {    private String name;    private Integer rollNumber;    private int m1;    private int m2;    private int m3;    private int totMarks;    //Getter setter}主类public class StudentData {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.println("Enetr the number of Student");        int totalStudent = sc.nextInt();        Map<Integer,Student> map = new TreeMap<Integer,Student>();        for(int i =0;i<totalStudent;i++) {            Student ss = new Student();            System.out.println("Enter the Student roll number");            ss.setRollNumber(sc.nextInt());            System.out.println("Enter the Student Name");            ss.setName(sc.next());            System.out.println("Enter the m1 marks ");            ss.setM1(sc.nextInt());            System.out.println("Enetr the m2 marks ");            ss.setM2(sc.nextInt());            System.out.println("Enter the m3 marks ");            ss.setM3(sc.nextInt());            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());            map.put(ss.getTotMarks(),ss);            ss=null;        }           //stdList.forEach(System.out::print);        for(Map.Entry<Integer,Student> m :map.entrySet()) {            System.out.println(m);        }    }}实际上,我正在使用 TreeMap 它按键对值进行排序(总分是我的 TreeMap 中的键)。但两个或更多学生的分数相同。然后旧学生对象(值)被新学生替换,因为 Key 不允许重复输出6=学生 [姓名=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]9=学生 [姓名=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]地图中存储的唯一唯一 totMarks
查看完整描述

3 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

由于您不能使用现有的 Comparator 或排序算法,因此您需要自己完成。我已经实现了一个static函数lessOrEqual,它接受 2 个Student实例,比较它们并返回是否s1小于或等于s2。 larger(Student s1, Student s2)仅当s1大于时返回真s2。可以有很多不同的方法来做到这一点,这真的取决于你,因为它只是一个比较。该函数首先检查成绩,如果成绩匹配,它将检查姓名并相应地返回。


编辑:如您所见,我替换lessOrEqual为larger因为我正在使用的选择排序需要找到larger。这是相同的效果,我这样做只是为了更好的可读性。


然后我实现了另一个static接受ArrayList<Student>、排序并返回排序的函数。使用的排序算法非常基本:选择排序。它的 O(N^2) 效率不高,但为了简单起见,我在下面的演示中这样做了。


代码:


import java.util.ArrayList; 


public class Student {

    private String name;

    private Integer rollNumber;

    private int m1;

    private int m2;

    private int m3;

    private int totMarks;


    public static boolean larger(Student s1, Student s2){

        if(s1.totMarks < s2.totMarks) return false; 

        else if (s1.totMarks > s2.totMarks) return true;

        // compare names

        else return s1.name.compareTo(s2.name) > 0;

    }


    public static ArrayList<Student> sortSelection(ArrayList<Student> list){

        for(int i=0; i<list.size(); i++){

            for(int j=i+1; j< list.size(); j++){

                if(larger(list.get(i), list.get(j))){ // swap

                    Student temp = list.get(i); 

                    list.set(i, list.get(j));

                    list.set(j, temp);

                }

            }

        }

        return list;

    }

    //Getter setter

    public String getName(){

        return name; 

    }


    public void setName(String name){

        this.name = name; 

    }


    public int getTotMarks(){

        return totMarks;

    }


    public void setTotMarks(int totMarks){

        this.totMarks = totMarks; 

    }


    @Override

    public String toString(){

        return String.format("Name: %20s - Total Marks: %3d", name, totMarks);

    }


    public static void main(String[] args){

        Student s1 = new Student(); 

        Student s2 = new Student();

        Student s3 = new Student();

        Student s4 = new Student();


        s1.setName("John Smith");

        s1.setTotMarks(98);

        s2.setName("Jack Smith");

        s2.setTotMarks(98);

        s3.setName("Adam Noob");

        s3.setTotMarks(100);

        s4.setName("Ved Parkash");

        s4.setTotMarks(99);


        ArrayList<Student> list = new ArrayList<>(); 

        list.add(s4);

        list.add(s3);

        list.add(s1);

        list.add(s2);


        System.out.println("Array before sorting:");

        for(int i=0; i<list.size(); i++){

            System.out.println(list.get(i).toString());

        }


        Student.sortSelection(list);


        System.out.println("Array after sorting:");

        for(int i=0; i<list.size(); i++){

            System.out.println(list.get(i).toString());

        }

    }

}

输出:


Array before sorting:

Name:          Ved Parkash - Total Marks:  99

Name:            Adam Noob - Total Marks: 100

Name:           John Smith - Total Marks:  98

Name:           Jack Smith - Total Marks:  98

Array after sorting:

Name:           Jack Smith - Total Marks:  98

Name:           John Smith - Total Marks:  98

Name:          Ved Parkash - Total Marks:  99

Name:            Adam Noob - Total Marks: 100

笔记:


1) 查看学生添加到列表中的顺序,它是 4,3, 1 然后是 2。这是为了证明它在成绩匹配时根据姓名排序(Jack Smith vs John Smith)。


2) 我对学生进行硬编码以制作更好的演示。


3) 正如您可能注意到的那样,我没有设置任何其他变量,因为问题完全是关于排序的,唯一对排序有贡献的变量是:name和totMarks。你将不得不做剩下的事情。


4) 我正在使用ArrayList,但不限于此,通过简单的更改,您可以在普通Student[]数组上使用它。


5)函数larger不一定是static,你可以把它做成一个成员函数,用不同的方式使用。例如,上面的代码将更改为:


    public boolean larger(Student other){

        if(totMarks < other.totMarks) return false; 

        else if (totMarks > other.totMarks) return true;

        // compare names

        else return name.compareTo(other.name) > 0;

    }


    public static ArrayList<Student> sortSelection(ArrayList<Student> list){

        for(int i=0; i<list.size(); i++){

            for(int j=i+1; j< list.size(); j++){

                // comparison way changes accordingly

                if(list.get(i).larger(list.get(j))){ // swap

                    Student temp = list.get(i); 

                    list.set(i, list.get(j));

                    list.set(j, temp);

                }

            }

        }

        return list;

    }


查看完整回答
反对 回复 2022-12-21
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

为了保持简单(即 KISS 原则)并解释我与复合键相关的“提示”,以下是工作示例。


解决方案的“关键”是让树自然地对数据进行排序(不是,恕我直言,通过提供手动排序来添加代码使其变得更加复杂)。因此,学生类需要返回一个树可以自然排序的键。


为了产生所需的排序结果,树的键是(总分,学生姓名)。


这是修改后的 Student 类(减去 getter 和 setter,但我确实添加了一个新的构造函数以使我的生活更轻松):


public class Student {

    private String name;

    private Integer rollNumber;

    private int m1;

    private int m2;

    private int m3;

    private int totMarks;

    //Getter setter


    public Student() {


    }


    public Student(String name, Integer rollNumber, int m1, int m2, int m3) {

        this.name = name;

        this.rollNumber = rollNumber;

        this.m1 = m1;

        this.m2 = m2;

        this.m3 = m3;

        this.totMarks = m1 + m2 + m3;

    }


    public String getKey() {

//      return String.format("%d-%s", totMarks, name);          // WRONG!

        return String.format("%04d-%s", totMarks, name);        // Right

    }


    public String toString() {

        return String.format("%06d: %s - %d", rollNumber, name, totMarks);

    }


}

请注意,方法中有一行注释掉的代码getKey带有注释WRONG。这与我用个位数分数测试的暗示有关。尝试交换两行代码以查看正确和错误的结果。


这是主要的,我删除了所有扫描仪的东西——再次让我的生活更轻松。希望您可以关注它并重新添加到您的扫描仪循环中。


import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.TreeMap;


public class StudentData {

    public static void main(String[] args) {

        // Initialise a list of students (as I don't want to rekey all the details each

        // time I run the program).

        List<Student> studentList = Arrays.asList(

                    new Student("Fred", 1, 2, 2, 2),      /* Score of 6 */

                    new Student("John", 2, 2, 3, 3),      /* Score of 8 */

                    new Student("Jane", 3, 20, 25, 30),      /* Score of 75 */

                    new Student("Julie", 4, 20, 15, 10)      /* Score of 45 */

                    // add as many new students as you like, and reorder them

                    // as much as you like to see if there is any difference in the

                    // result (there shouldn't be).

        );


            // Note the key of the tree is of type String - not Integer.

            // This is the heart of the algorithm, the tree will be "sorted"

            // on the natural key provided. This "natural key" is in fact

            // a compound key that is generated by combining the total score

            // and the student name.

        Map<String,Student> map = new TreeMap<String,Student>();

        for (Student ss : studentList) {

            map.put(ss.getKey(),ss);

        }   

        //stdList.forEach(System.out::print);

        for(Map.Entry<String,Student> m :map.entrySet()) {

            System.out.println(m);

        }

    }

}

我希望您同意这是一个更简单的解决方案。还有一个潜在的性能优势,因为学生在被加载到树中时被排序(即一次)。我认为这种排序的性能是 log(n)。检索排序可能是 n log(n) 或更糟。


查看完整回答
反对 回复 2022-12-21
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

不是将值存储为 student,而是将它们存储为 (name, student) 的映射,这样当遇到具有相同标记的学生时,就会将其添加到映射中。


public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enetr the number of Student");

    int totalStudent = sc.nextInt();

    Map<Integer, Map<String, Student>> map = new TreeMap<>();

    for(int i =0;i<totalStudent;i++) {

        Student ss = new Student();

        System.out.println("Enter the Student roll number");

        ss.setRollNumber(sc.nextInt());

        System.out.println("Enter the Student Name");

        ss.setName(sc.next());

        System.out.println("Enter the m1 marks ");

        ss.setM1(sc.nextInt());

        System.out.println("Enetr the m2 marks ");

        ss.setM2(sc.nextInt());

        System.out.println("Enter the m3 marks ");

        ss.setM3(sc.nextInt());

        ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());


        Integer key = ss.getTotMarks();

        if (map.get(key) == null){  // if this is a new key in the map, then create a new TreeMap and put it

            final TreeMap<String, Student> nameAndStudentMap = new TreeMap<>();

            nameAndStudentMap.put(ss.getName(), ss);

            map.put(key, nameAndStudentMap);

        }else { // if the key already existed, then get the map stored and add to it.

            map.get(key).put(ss.getName(), ss);

        }


    }

    //stdList.forEach(System.out::print);

    for(Map.Entry<Integer,Map<String, Student>> m :map.entrySet()) {

        for (Map.Entry<String, Student> nameAndStudent : m.getValue().entrySet()) {

            System.out.println(m.getKey() + " = " + nameAndStudent.getValue());

        }

    }


}


查看完整回答
反对 回复 2022-12-21
  • 3 回答
  • 0 关注
  • 80 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信