Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list by POJO property in descending order?

Tags:

java

list

sorting

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
like image 371
programminglover Avatar asked Jun 04 '15 11:06

programminglover


People also ask

How do you sort an array of objects in Java in descending order?

reverseOrder() method. Array elements can be sorted in descending order by passing in the array and Collections. reverseOrder() as parameters to Arrays. sort().

How do you list an array in descending order?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections. reverseOrder() as the parameter and returns a Collection sorted in the Descending Order.

How do you sort a list in reverse order?

In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.


1 Answers

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!

like image 88
Mena Avatar answered Oct 12 '22 19:10

Mena