Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 511
Milli Szabo Avatar asked Nov 23 '10 17:11

Milli Szabo


People also ask

What does Collection sort () do?

Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.

What is the complexity of collections sort?

The time complexity of Collections. sort() is O(n*log(n)) and a list sorted with Collections. sort() will only be sorted after the call to sort(). The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).

How do I sort a List by multiple fields?

To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.


1 Answers

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; } 
like image 77
Jason S Avatar answered Sep 22 '22 03:09

Jason S