0

I have a List of entities, and I want to be able to sort the List using a custom .sort() function which takes as parameter the way the list should be sorted. e.g.

repo.sort(sort by field) 
repo.sort(sort by field but ascending) 
repo.sort(sort by field descending and by another field ascending)

My train of thought was that i should make a sort function that gets overloaded and depending on the number of parameters it should behave a certain way, but i feel that i am overcomplicating it and was wondering if there is a simpler way. Thank you in advance.

Demetrius
  • 13
  • 4
  • Using https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator- with a custom Comparator. – PeterMmm Apr 13 '22 at 19:50
  • 1
    `persons.sort(Comparator.comparing(Person::getName).thenComparingInt(Person::getAge().reversed());` as a small example showcasing everything you mentioned. – Zabuzard Apr 13 '22 at 20:50

1 Answers1

-1

Comparator is an interface and as such it has to have unified method definitions. There are a couple of ways to handle what you want, but not by parameter in the predefined method signatures:

  1. Create several custom Comparator, one for each field(s) to use.
  2. Create a single Comparator with predefined settings and you add a setter method to have it use those configurations.

I would add that you should NOT write a Comparator to handle reverse ordering. Use the methods available to you through the Collections utility, namley Collections.reverse()

Ryan
  • 1,762
  • 6
  • 11
  • This mimicks to great extent functionality provided by static methods in `Comparator`. Also `Collections.reverse()` will reverse the collection, not the ordering from a comparator(by particular field in this exact case). This method is not applicable when working with comparators. – Chaosfire Apr 13 '22 at 21:29