0

With this class:

public class MyClass implements Comparable<MyClass> {

    private String status;
    private String name;
    private String firstName;  

    @Override
    public int compareTo(MyClass o) {
        return 0;
    }

}

I'd like to sort a list of MyClass objects with this order:

  • Firstly, status = "open", then "working" then, "close"
  • Secondly, name = "toto", then "titi"
  • Finally, firstName = "tutu", "tata"

How can I do this with the Comparable interface ?

Michael
  • 41,989
  • 11
  • 82
  • 128
  • 5
    Well, what have you tried so far? – DGK Jun 29 '18 at 09:29
  • https://stackoverflow.com/questions/369512/how-to-compare-objects-by-multiple-fields I tried the third answer in this post assuming I'm not using java 8. My filters are not the same, I don't know how to check by "keys" – whySoSerious Jun 29 '18 at 09:32
  • Are these the only available names? I.e. `toto`, `titi`, `tutu`, `tata`? If not, then what's the general rule for sorting? Anyway, here is how you can use the comparator: `List list = ...; Collections.sort(list);` – Tamas Rev Jun 29 '18 at 09:38

1 Answers1

0

I would do this like so: first define a set of lists which define the order for each field:

private static List<String> statusOrder = Arrays.asList("open", "working", "close");
private static List<String> nameOrder = Arrays.asList("toto", "titi");
private static List<String> firstNameOrder = Arrays.asList("tutu", "tata");

Then use List.indexOf to get the position of the element in the list, and then simply subtract the results:

@Override
public int compareTo(MyClass o) {
    final int statusComp = statusOrder.indexOf(status) - statusOrder.indexOf(o.status);
    if (statusComp != 0) return statusComp;
    final int nameComp = nameOrder.indexOf(name) - nameOrder.indexOf(o.name);
    if (nameComp != 0) return nameComp;
    return firstNameOrder.indexOf(firstName) - firstNameOrder.indexOf(o.firstName);
}

The issue with this approach is that indexOf will return -1 if the element is not in the list. You would need to define the behaviour in the case where MyClass contains non-standard values (perhaps it will never happen).

Michael
  • 41,989
  • 11
  • 82
  • 128
  • @DidierL I thought the agreement was sarcastic? I don't see it as an exact duplicate. That question wants to sort multiple string fields alphabetically, this question wants to sort multiple string fields, each with a defined non-alphabetic order. I've tried to improve the question to make it a clearer non-dupe. – Michael Jun 29 '18 at 09:53
  • Ok, let's leave it open then. – Didier L Jun 29 '18 at 12:12