按多个字段对对象列表排序

编程入门 行业动态 更新时间:2024-10-23 07:18:36
本文介绍了按多个字段对对象列表排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个Java对象列表,我想根据多个字段排序。

I have a List of Java objects that I want to sort according to more than one field.

public class graduationCeremony { String campus; String faculty; String building; }

是否可以使用 Comparator 或 Comparable 接口根据多个字段对列表排序?我看到的所有例子只根据一个字段排序。换句话说,人们可以通过校园或教师或建筑来排序。我想按照校园,然后是教师,然后是建筑来排序(如在SQL中存在: ORDER BY campus,faculty,building )

Is it possible to use a Comparator or the Comparable interface to sort the list according to multiple fields? All the examples I have seen sort according to only one field. In other words, one can sort by 'campus' OR 'faculty' OR 'building'. I want to sort by 'campus', then 'faculty', then 'building' (as it exists in SQL: ORDER BY campus, faculty, building)

我认为这个问题已经问前,但我不明白接受的答案。

I think this question has been asked before, but I don't understand the accepted answer. Can someone expand or illustrate this answer?

推荐答案

您的比较器将如下所示:

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<graduationCeremony> { public int compare(graduationCeremony o1, graduationCeremony o2) { int value1 = o1.campuspareTo(o2.campus); if (value1 == 0) { int value2 = o1.facultypareTo(o2.faculty); if (value2 == 0) { return o1.buildingpareTo(o2.building); } else { return value2; } return value1; } }

基本上它会继续比较你的类的每个连续属性到目前为止,比较的属性是相等的( == 0 )。

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

更多推荐

按多个字段对对象列表排序

本文发布于:2023-11-22 13:54:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字段   对象   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!