0

Arraylist contains class model. Class has a parameter 'status' whose values would be 'open' , 'close' , ' upcoming '.

How to sort the arraylist based on ' status ' parameter i.e. 'open' should appear first, 'close' & 'upcoming' will be following to it respectively ?

Any help appreciated..

2 Answers2

1

You just need to implement the Comparable interface to your model class

Then implement the compareTo method with your compare logic.

And call Collections.sort(yourModelList); to make it.

You can find an example of implementing the Comparable interface here.

Hope this helps.

Community
  • 1
  • 1
Nanoc
  • 2,381
  • 1
  • 20
  • 35
-1

Unless the elements in your list have a notion of natural ordering, do not change YourClass to implement Comparable<YourClass>.

Instead, implement a Comparator<YourClass>, which is an entirely separate class:

class YourClassComparator implements Comparator<YourClass> {
  @Override
  public int compare(YourClass a, YourClass b) {
    // ... 
  }
}

and then pass an instance of this to Collections.sort:

Collections.sort(yourModelList, new YourClassComparator());
Andy Turner
  • 137,514
  • 11
  • 162
  • 243