Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort list of classes in java

How can I sort ascending/descending this list of classes by id in Java?

[Complaints{id=1, state='inregistrata'}, Complaints{id=3, state='solutionata'}, Complaints{id=2, state='solutionata'}]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do this by using Java’s Comparable interface.

The Comparable interface is used to make instances comparable with each other. It works by implementing the interface’s compareTo() method. The way it works is simple;

Let’s say we have two objects; o1 and o2. compareTo() returns an integer that carries information about the comparison of the two instances.

  • If o1 > o2, then compareTo() should return an integer >0.
  • If o1 < o2, then compareTo() should return an integer <0.
  • Finally, ff o1 == o2, then compareTo() should return exactly 0.

You can base the comparison on whichever attribute you like. An implementation that might work for you follows;

First, in your Complaint class implement the Comparable interface like this;

public class Complaint implements Comparable<Complaint> {
   ...
}

Then, implement compareTo() like this;


public class Complaint implements Comparable<Complaint> {
    private int id;
    private String state;

    //... other code ...

    public int getId(){
        return this.id;
    }

    @Override
    public int compareTo(Complaint c) {
        if (this.id == c.getId()) {
            return 0;
        } else if (this.id > c.getId()){
            return 1;
        } else {
            return -1;
        }
    }
}

Once you do the above, you can now use Java’s Collections.sort() method to sort your complaint instances.

List complaints = new ArrayList<Complaint>();
complaints.add(new Complaint(2, "solutionata"));
complaints.add(new Complaint(1, "inregistrata"));
complaints.add(new Complaint(3, "solutionata"));

Collections.sort(complaints); // sort in ascending order 
Collections.reverse(complaints); // sort in descending order

Do not forget to import Collections:

import java.util.Collections;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading