7

I have POJO class Student like this

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

I am creating ArrayList like this

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
Pshemo
  • 122,468
  • 25
  • 185
  • 269
programminglover
  • 753
  • 3
  • 10
  • 20
  • possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – guy_sensei Jun 04 '15 at 11:33

6 Answers6

12

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 Comparable interface:

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);
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • 1
    To compare `int` you can use `Integer.compare(int1, int2)`. There is no need to box `int` to `Integer` just to call `compareTo`. – Pshemo Jun 04 '15 at 11:39
  • Thanks @Pshemo, I'm more used to C# where you can just call `.compareTo` on an `int`. – Glorfindel Jun 04 '15 at 11:43
  • i think My JDK 6 version is not supporting it but Some part of your answer have helped me that's why I am upvoting you and marking @Mena answer correct I am very thankful of you for your efforts – programminglover Jun 04 '15 at 12:26
12

You can use a custom 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 Student class, if the only (or default) sorting will be by score.#

Second edit

In order to sort in a decreasing order, you can replace the return statement in your Comparator with the following:

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

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

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
10

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

al_students.sort(Comparator.comparingInt(Student::getScore).reversed());
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

You can write the custom Comparator to solve this.

Sonu Gupta
  • 347
  • 3
  • 16
0

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.

Kishore Kumar Korada
  • 1,204
  • 6
  • 22
  • 47
0

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 post explaining when to use Comparable and when to use Comparator.

That will be really helpful to you.

FatherMathew
  • 960
  • 12
  • 15