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

查看:33
本文介绍了具有多个字段的 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天全站免登陆