java 如何在java中对由pojo类组成的Arraylist进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30642633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:25:52  来源:igfitidea点击:

How to sort Arraylist consisting of pojo class in java

javasortingarraylist

提问by programminglover

I have POJO class Student like this

我有这样的 POJO 班学生

class Student
{
    private int score;
    private String FirstName;
    //Getters and setters .................
}

I am creating ArrayList like this

我正在像这样创建 ArrayList

public static void main(String[] args)
{
    List<Student> al_students= new ArrayList<Student>();
    Student s1= new Student();
    s1.setScore(90);
    s1.setFirstName("abc");
    al_students.add(s1);

    Student s2= new Student();
    s2.setScore(95);
    s2.setFirstName("def");
    al_students.add(s2);

    Student s3= new Student();
    s3.setScore(85);
    s3.setFirstName("xyz");
    al_students.add(s3);
}

Now I want to sort it based on scores in descending order i.e
output

现在我想根据降序的分数对其进行排序,即
输出

1)def      95
2)abc      90
3)xyz      85

回答by Glorfindel

Use a Comparator:

使用比较器

    Collections.sort(al_students, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return Integer.compare(o2.getScore(), o1.getScore());
        }           
    });

Alternatively, have Student implement the Comparableinterface:

或者,让 Student 实现Comparable接口:

class Student implements Comparable<Student> {
    ...
    @Override
    public int compareTo(Student s) {
        return Integer.compare(s.getScore(), getScore());
    }
}

Then you can just sort without the Comparator:

然后你可以在没有比较器的情况下进行排序:

Collections.sort(al_students);

回答by Mena

You can use a custom Comparator.

您可以使用自定义Comparator.

Here's a full example (imports excluded):

这是一个完整的示例(不包括进口):

public class Main {

    // main method setting up and printing students
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>();
        Student s1 = new Student();
        s1.setScore(90);
        s1.setFirstName("abc");
        students.add(s1);

        Student s2 = new Student();
        s2.setScore(95);
        s2.setFirstName("def");
        students.add(s2);

        Student s3 = new Student();
        s3.setScore(85);
        s3.setFirstName("xyz");
        students.add(s1);
        System.out.printf("Unordered: %s%n", students);
        // sorting using anonymous Comparator
        Collections.sort(students, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                // notice the cast to (Integer) to invoke compareTo
                return ((Integer)s1.getScore()).compareTo(s2.getScore());
            }
        });
        System.out.printf("Ordered: %s%n", students);
    }
    // Student class
    static class Student {
        private int score;
        private String firstName;
        // boring stuff
        public int getScore() {
            return score;
        }

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

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String name) {
            this.firstName = name;
        }
        // for printing
        @Override
        public String toString() {
            return String.format("Student \"%s\" with score: %d%n", firstName,
                    score);
        }
    }
}

Output

输出

Unordered: [Student "abc" with score: 90
, Student "def" with score: 95
, Student "abc" with score: 90
]
Ordered: [Student "abc" with score: 90
, Student "abc" with score: 90
, Student "def" with score: 95
]

Note

笔记

As others mention, you can also implement Comparable<Student>in your Studentclass, if the only (or default) sorting will be by score.#

正如其他人提到的,你也可以implement Comparable<Student>在你的Student班级中,如果唯一(或默认)排序是按分数。#

Second edit

第二次编辑

In order to sort in a decreasing order, you can replace the returnstatement in your Comparatorwith the following:

为了按降序排序,您可以将您的return语句替换Comparator为以下内容:

return ((Integer)s2.getScore()).compareTo(s1.getScore());

Thanks programmingloverfor spotting this / apologies for mistakenly rejecting the edit!

感谢编程爱好者发现这一点/为错误地拒绝编辑而道歉!

回答by Pshemo

If you are using Java 8 then your code can look like

如果您使用的是 Java 8,那么您的代码可能如下所示

al_students.sort(Comparator.comparingInt(Student::getScore).reversed());

回答by Sonu Gupta

You can write the custom Comparatorto solve this.

您可以编写自定义Comparator来解决此问题。

回答by Kishore Kumar Korada

See, Have this logic.
Student is a class which you've created. And If you want to allow some other class to sort your custom objects in your own requirements, you should tell it. And that's gonna happen if you implement either Comparable or Comparator interface and override those method in your custom class and in those methods you specify how you are gonna compare.

看,有这个逻辑。
Student 是您创建的类。如果您想允许其他类根据您自己的要求对自定义对象进行排序,您应该告诉它。如果您实现 Comparable 或 Comparator 接口并在您的自定义类中覆盖这些方法,并且在这些方法中您指定要比较的方式,就会发生这种情况。

回答by FatherMathew

Almost the entire question is answered by others....

几乎整个问题都由其他人回答......

Since there are 2 options, either to use Comparable interface or Comparator interface, I would like you to go to this postexplaining when to use Comparable and when to use Comparator.

由于有 2 个选项,要么使用 Comparable 接口,要么使用 Comparator 接口,我希望你去这篇文章解释何时使用 Comparable 以及何时使用 Comparator。

That will be really helpful to you.

这对你真的很有帮助。