Home > Back-end >  How to sort elements of List<EObject>?
How to sort elements of List<EObject>?

Time:12-22

I want to sort EObject elements in List wrt to the name in ascending order. I tried using the below code but I am getting compiler error.

I tried:

List<EObject> list = new ArrayList<EObject>();
list.sort(Comparator.naturalOrder());

CodePudding user response:

EObject must be a comparable object to be sorted by java. In your object class definition you need to use implements Comparable. You then need to override the compareTo() method from the comparable interface with a set of arguments that sets the sorting precedent for the objects.

CodePudding user response:

You could use Collections.sort(list, comparator)

Here's an example:

Collections.sort(list, (o1,o2)->o1.name.compareTo(o2.name));

CodePudding user response:

You can do it one of two ways.

  • Implement the Comparable interface in your class. This creates a natural ordering for your object.
public class EObject implements Comparable<EObject>{
     private String name;
       // perhaps other fields, constructors, and getters/setters
     public EObject(String name) {
         this.name = name;
     }
    public String getName() {
        return name;
    }
    @Override
    public int compareTo(EObject ob) {
        // since you are comparing Strings, use String's compareTo method
        return name.compareTo(ob.name);
    }
    public String toString() {
        return name;
    }
}

Some data

List<EObject>  list = new ArrayList<>(List.of(
            new EObject("A"),
            new EObject("X"),
            new EObject("Y"),
            new EObject("H"),
            new EObject("F"),
            new EObject("B"),
            new EObject("G"),
            new EObject("R"),
            new EObject("S")));

list.sort(null); // null says use natural order

prints

[A, B, F, G, H, R, S, X, Y]

And this will reverse the natural order you implemented

list.sort(Comparator.reverseOrder());
System.out.println(list);

prints

[Y, X, S, R, H, G, F, B, A]
  • If you have not implemented the Comparable interface you can do the above like this.
list.sort(Comparator.comparing(EObject::getName));
// or for reversed order of names
list.sort(Comparator.comparing(EObject::getName).reversed());
  • Related