如何从 Java Object/ArrayList 中排序和获取最高值 [英] How to sort and get highest value from Java Object/ArrayList

查看:40
本文介绍了如何从 Java Object/ArrayList 中排序和获取最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含学生对象的 ArrayList(姓名、数学分数、物理分数).如何对 ArrayList 进行排序并使用第一个最高数字/秒进行编辑,然后是第二大数字,然后是第三大数字,依此类推.例如我有下面的对象值:

I have an ArrayList with Student Objects (Name, Mark in Math, Mark in Physics). How can I sort the ArrayList and edit with first highest number/s, then second highest then third and so on. For example I have the object value below:

ArrayList<> allStudents = new ArrayList();
allStudents.add(new Student("A", 80, 94) );
allStudents.add(new Student("B", 98, 91) );
allStudents.add(new Student("F", 70, 84) );
allStudents.add(new Student("C", 98, 92) );
allStudents.add(new Student("H", 99, 93) );

我将查找编号最高的学生,我得到了 H.我编辑了对象,如:H"、97、90 并将其保存回该 ArraList.我再次寻找第二高,但在这里我有学生B"和C",我可以看到他们在数学中的数字相同,但在物理中 C 的数字最高,所以我将编辑C"、96、90 并将其保存回ArrayList 等等.这里哪个学生已经编辑过,我不会把它们拿来编辑和保存等等.如果有人请帮助我!提前致谢

I will look for the student with highest number, I got H. I edit the object like: "H", 97, 90 and save it back to that ArraList. Again I look for 2nd highest but here I have students "B" and "C", I can see they same number in math but in Physics C has highest number so I will edit "C", 96, 90 and save it back to the ArrayList and so on. Here which student already edited, I will not fetch them for edit and save thr and so on. IF someone please help me! Thanks in advance

推荐答案

你需要创建一个比较器,它可以是匿名的,也可以是一个类,并在你的 Student 中为你的标记做一个 get 方法,这样你可以在比较器内部使用它来比较排序的标记

You need to create a Comparator it can be anonymous or a class and in your Student do a get method for your mark so you can use it inside the comparator to compare the marks for sorting

示例:

ArrayList<Student> allStudents = new ArrayList();
        allStudents.add(new Student("A", 80, 94));
        allStudents.add(new Student("B", 98, 91));
        allStudents.add(new Student("F", 70, 84));
        allStudents.add(new Student("C", 98, 92));
        allStudents.add(new Student("H", 99, 93));

        Collections.sort(allStudents, new Comparator<Student>() {

            public int compare(Student s, Student s2) {
                return s.getMark() - s2.getMark();
            }
        });

这篇关于如何从 Java Object/ArrayList 中排序和获取最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆