Search code examples
javasortingcollections

Collections.sort with multiple fields


I have a list of "Report" objects with three fields (All String type)-

ReportKey
StudentNumber
School

I have a sort code goes like-

Collections.sort(reportList, new Comparator<Report>() {

@Override
public int compare(final Report record1, final Report record2) {
      return (record1.getReportKey() + record1.getStudentNumber() + record1.getSchool())                      
        .compareTo(record2.getReportKey() + record2.getStudentNumber() + record2.getSchool());
      }

});

For some reason, I don't have the sorted order. One advised to put spaces in between fields, but why?

Do you see anything wrong with the code?


Solution

  • Do you see anything wrong with the code?

    Yes. Why are you adding the three fields together before you compare them?

    I would probably do something like this: (assuming the fields are in the order you wish to sort them in)

    @Override public int compare(final Report record1, final Report record2) {
        int c;
        c = record1.getReportKey().compareTo(record2.getReportKey());
        if (c == 0)
           c = record1.getStudentNumber().compareTo(record2.getStudentNumber());
        if (c == 0)
           c = record1.getSchool().compareTo(record2.getSchool());
        return c;
    }