Home > database >  How to sort list of classes in java
How to sort list of classes in java

Time:01-16

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'}]

CodePudding user response:

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;

  •  Tags:  
  • java
  • Related