具有多个字段的Collections.sort [英] Collections.sort with multiple fields

查看:147
本文介绍了具有多个字段的Collections.sort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个字段(所有字符串类型)的报表对象列表 -

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?

推荐答案


您看到代码有什么问题吗?

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;
}

这篇关于具有多个字段的Collections.sort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆