文学起点网
当前位置: 首页 文学百科

java对象根据某个属性排序(Java对象排序详解)

时间:2023-07-28 作者: 小编 阅读量: 2 栏目名: 文学百科

很难想象有Java开发人员不曾使用过Collection框架。在本文中,我将主要关注排序Collection的ArrayList、HashSet、TreeSet,以及最后但并非最不重要的数组。在不转换为ArrayList的情况下,可以通过使用TreeSet来实现排序。TreeSet是Set的另一个实现,并且在使用默认构造函数创建Set时,使用自然排序进行排序。到目前为止,一切都如期工作,排序似乎是一件轻而易举的事。现在让我们尝试在各个Collection中存储自定义对象,并查看排序是如何工作的。

很难想象有Java开发人员不曾使用过Collection框架。在Collection框架中,主要使用的类是来自List接口中的ArrayList,以及来自Set接口的HashSet、TreeSet,我们经常处理这些Collections的排序。

在本文中,我将主要关注排序Collection的ArrayList、HashSet、TreeSet,以及最后但并非最不重要的数组。

让我们看看如何对给定的整数集合(5,10,0,-1)进行排序:

数据(整数)存储在ArrayList中

private void sortNumbersInArrayList() {

List<Integer> integers = new ArrayList<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original list: "integers);

Collections.sort(integers);

System.out.println("Sorted list: " integers);

Collections.sort(integers, Collections.reverseOrder());

System.out.println("Reversed List: "integers);

}

输出:

Original list: [5, 10, 0, -1]

Sorted list: [-1, 0, 5, 10]

Reversed List: [10, 5, 0, -1]

数据(整数)存储在HashSet中

private void sortNumbersInHashSet() {

Set<Integer> integers = new HashSet<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original set: "integers);

// Collections.sort(integers); This throws error since sort method accepts list not collection

List list = new ArrayList(integers);

Collections.sort(list);

System.out.println("Sorted set: " list);

Collections.sort(list, Collections.reverseOrder());

System.out.println("Reversed set: "list);

}

输出:

Original set: [0, -1, 5, 10]

Sorted set: [-1, 0, 5, 10]

Reversed set: [10, 5, 0, -1]

在这个例子中(数据(整数)存储在HashSet中),我们看到HashSet被转换为ArrayList进行排序。在不转换为ArrayList的情况下,可以通过使用TreeSet来实现排序。TreeSet是Set的另一个实现,并且在使用默认构造函数创建Set时,使用自然排序进行排序。

数据(整数)存储在TreeSet中

private void sortNumbersInTreeSet() {

Set<Integer> integers = new TreeSet<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original set: "integers);

System.out.println("Sorted set: "integers);

Set<Integer> reversedIntegers = new TreeSet(Collections.reverseOrder());

reversedIntegers.add(5);

reversedIntegers.add(10);

reversedIntegers.add(0);

reversedIntegers.add(-1);

System.out.println("Reversed set: "reversedIntegers);

}

输出:

Original set: [-1, 0, 5, 10]

Sorted set: [-1, 0, 5, 10]

Reversed set: [10, 5, 0, -1]

在这种情况下,“Original set:”和“Sorted set:”两者相同,因为我们已经使用了按排序顺序存储数据的TreeSet,所以在插入后不用排序。

到目前为止,一切都如期工作,排序似乎是一件轻而易举的事。现在让我们尝试在各个Collection中存储自定义对象(比如Student),并查看排序是如何工作的。

数据(Student对象)存储在ArrayList中

private void sortStudentInArrayList() {

List<Student> students = new ArrayList<>();

Student student1 = createStudent("Biplab", 3);

students.add(student1);

Student student2 = createStudent("John", 1);

students.add(student2);

Student student3 = createStudent("Pal", 5);

students.add(student3);

Student student4 = createStudent("Biplab", 2);

students.add(student4);

System.out.println("Original students list: "students);

Collections.sort(students);// Error here

System.out.println("Sorted students list: "students);

Collections.sort(students, Collections.reverseOrder());

System.out.println("Reversed students list: "students);

}

private Student createStudent(String name, int no) {

Student student = new Student();

student.setName(name);

student.setNo(no);

return student;

}

public class Student {

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{"

"name='"name'\''

", no="no

'}';

}

}

这会抛出编译时错误,并显示以下错误消息:

sort(java.util.List<T>)

in Collections cannot be applied

to (java.util.List<com.example.demo.dto.Student>)

reason: no instance(s) of type variable(s) T exist so that Student

conforms to Comparable<? Super T>

为了解决这个问题,要么Student类需要实现Comparable,要么需要在调用Collections.sort时传递Comparator对象。在整型情况下,排序方法没有错误,因为Integer类实现了Comparable。让我们看看,实现Comparable或传递Comparator如何解决这个问题,以及排序方法如何实现Collection排序。

使用Comparable排序

package com.example.demo.dto;

public class Student implements Comparable{

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{"

"name='"name'\''

", no="no

'}';

}

@Override

public int compareTo(Object o) {

return this.getName().compareTo(((Student) o).getName());

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

在所有示例中,为了颠倒顺序,我们使用“Collections.sort(students, Collections.reverseOrder()”,相反的,它可以通过改变compareTo(..)方法的实现而达成目标,且compareTo(…) 的实现看起来像这样 :

@Override

public int compareTo(Object o) {

return (((Student) o).getName()).compareTo(this.getName());

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

Reversed students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

如果我们观察输出结果,我们可以看到“Sorted students list:”以颠倒的顺序(按学生name)输出学生信息。

到目前为止,对学生的排序是根据学生的“name”而非“no”来完成的。如果我们想按“no”排序,我们只需要更改Student类的compareTo(Object o)实现,如下所示:

@Override

public int compareTo(Object o) {

return (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='John', no=1}, Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}]

在上面的输出中,我们可以看到“no”2和3的两名学生具有相同的名字“Biplab”。

现在假设我们首先需要按“name”对这些学生进行排序,如果超过1名学生具有相同姓名的话,则这些学生需要按“no”排序。为了实现这一点,我们需要改变compareTo(…)方法的实现,如下所示:

@Override

public int compareTo(Object o) {

int result = this.getName().compareTo(((Student) o).getName());

if(result == 0) {

result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

return result;

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

使用Comparator排序

为了按照“name”对Students进行排序,我们将添加一个Comparator并将其传递给排序方法:

public class Sorting {

private void sortStudentInArrayList() {

List<Student> students = new ArrayList<>();

Student student1 = createStudent("Biplab", 3);

students.add(student1);

Student student2 = createStudent("John", 1);

students.add(student2);

Student student3 = createStudent("Pal", 5);

students.add(student3);

Student student4 = createStudent("Biplab", 2);

students.add(student4);

System.out.println("Original students list: "students);

Collections.sort(integers, new NameComparator());

System.out.println("Sorted students list: "students);

}

}

public class Student {

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{"

"name='"name'\''

", no="no

'}';

}

}

class NameComparator implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

return o1.getName().compareTo(o2.getName());

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

同样,如果我们想按照“no”对Students排序,那么可以再添加一个Comparator(NoComparator.java),并将其传递给排序方法,然后数据将按“no”排序。

现在,如果我们想通过“name”然后“no”对学生进行排序,那么可以在compare(…)内结合两种逻辑来实现。

class NameNoComparator implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

int result = o1.getName().compareTo(o2.getName());

if(result == 0) {

result = o1.getNo() < o2.getNo() ? -1 : o1.getNo() == o2.getNo() ? 0 : 1;

}

return result;

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]

数据(Students对象)存储在Set中

在Set的这个情况下,我们需要将HashSet转换为ArrayList,或使用TreeSet对数据进行排序。此外,我们知道要使Set工作,equals(…)和hashCode()方法需要被覆盖。下面是基于“no”字段覆盖equals和hashcode的例子,且这些是IDE自动生成的代码。与Comparable或Comparator相关的其他代码与ArrayList相同。

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || getClass() != o.getClass()) return false;

Student student = (Student) o;

return no == student.no;

}

@Override

public int hashCode() {

return Objects.hash(no);

}

数据(Students对象)存储在数组中

为了对数组排序,我们需要做与排序ArrayList相同的事情(要么执行Comparable要么传递Comparable给sort方法)。在这种情况下,sort方法是“Arrays.sort(Object[] a )”而非“Collections.sort(..)”。

private void sortStudentInArray() {

Student [] students = new Student[4];

Student student1 = createStudent("Biplab", 3);

students[0] = student1;

Student student2 = createStudent("John", 1);

students[1] = student2;

Student student3 = createStudent("Pal", 5);

students[2] = student3;

Student student4 = createStudent("Biplab", 2);

students[3] = student4;

System.out.print("Original students list: ");

for (Student student: students) {

System.out.print( student" ,");

}

Arrays.sort(students);

System.out.print("\nSorted students list: ");

for (Student student: students) {

System.out.print( student" ,");

}

Arrays.sort(students, Collections.reverseOrder());

System.out.print("\nReversed students list: " );

for (Student student: students) {

System.out.print( student" ,");

}

}

//Student class

// All properties goes here

@Override

public int compareTo(Object o) {

int result =this.getName().compareTo(((Student)o).getName());

if(result ==0) {

result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

return result;

}

输出:

Original students list: Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,Student{name='Biplab', no=2} ,

Sorted students list: Student{name='Biplab', no=2} ,Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,

Reversed students list: Student{name='Pal', no=5} ,Student{name='John', no=1} ,Student{name='Biplab', no=3} ,Student{name='Biplab', no=2} ,

结论

我们经常对Comparable/Comparator的使用以及何时使用哪个感到困惑。下面是我总结的Comparable/Comparator的使用场景。

Comparator:

  • 当我们想排序一个无法修改的类的实例时。例如来自jar的类的实例。
  • 根据用例需要排序不同的字段时,例如,一个用例需要通过“name”排序,还有个想要根据“no”排序,或者有的用例需要通过“name和no”来排序。

Comparable:

应该在定义类时知道排序的顺序时使用,并且不会有其他任何需要使用Collection /数组来根据其他字段排序的情况。

注意:我没有介绍Set / List的细节。我假设读者已经了解了这些内容。此外,没有提供使用Set / array进行排序的详细示例,因为实现与ArrayList非常相似,而ArrayList我已经详细给出了示例。

最后,感谢阅读。

    推荐阅读
  • 苏州旅游攻略景点必去(苏州旅游必去景点有哪些)

    位于苏州市东北街一百七十八号,始建于明朝正德年间。虎丘是AAAAA级景区及全国文明单位,首批十佳文明风景旅游区示范点。中午,周庄最为欢闹,游人穿梭熙熙攘攘,船儿来回摇摇荡荡,各地的游客与热情的商铺融为一体,热闹非凡,安静的古镇着实多了些欢闹的气息。狮子林为苏州四大名园之一,位于苏州市市城东北园林路。

  • 买的玉米种子是瘪的(去年买的玉米种子剩了很多)

    去年买的陈玉米种子建议不要用针对去年的陈玉米种子,大多情况下不建议再次使用,会影响到玉米后期的生长和产量情况。陈年的因为保管的问题,可能会出现很多因素影响玉米的出苗率或者后期的生长。陈玉米种子隔了一年后再种植,种子自身水分含量降低,水分降低严重的情况下,影响播种的效率和玉米的后期生长,由于活性降低,即使能出芽,也不一定能出苗。

  • 173.2亿!国庆消费火爆 国庆消费市场

    今年国庆、重阳两节叠加,全省消费市场呈现平衡较快增长态势,服装、家电、汽车等商品消费亮点突出,大众餐饮、旅行休闲、文体娱乐等主要服务消费备受青睐。根据商务部业务统一平台生存必需品监测系统显示,国庆黄金周期间,全省生存必需品市场供应充沛,价格总体平衡。除了买买买,国庆还是婚庆、团圆、会友高峰,各地亲友聚餐、婚寿宴等大众化餐饮生意兴隆。

  • 吴承恩是怎么写出的西游记(吴承恩怎么写出的西游记)

    吴承恩怎么写出的西游记诸葛长青:吴承恩写西游记诸葛长青:吴承恩怎么写出的《西游记》西游记,广泛流传西游记,作者吴承恩西游记,包含了儒释道大智慧那么,吴承恩是怎么写出的《西游记》呢?诸葛长青把自己对吴承恩写《西游记》,研究成。

  • 李逵扮演者(大家一起来看看吧)

    我们一起去了解并探讨一下这个问题吧!李逵扮演者赵小锐的李逵应该算是很多人印象当中的经典所在了,他的李逵也是很粗犷,但是这种粗犷当中却带着细腻,也是因为这个角色,他开始受到了不少的观众的关注和喜爱。其实之前的他也有出演过一些电视剧的,但是可惜的是一直都没能够真正的红起来,是李逵这个角色,让他一夜成名爆火了。

  • 汽车空间大小怎么看轴距(什么因素会影响车内空间)

    大众速腾,长度4655mm,轴距2651mm。看外观就明白了,因为宝马320i是后驱车,发动机采用纵置布局;而大众速腾是前驱车,发动机采用横置布局。而且由于发动机纵置,后驱设计,对于车内空间侵占较为严重,所以宝马320的长轴距实际上对于空间的帮助是“虚高”的。前面我们就提到了,宝马3系采用了后驱,大众速腾采用了前驱。回到我们的主题,通常来说,麦弗逊与扭力梁对于车辆空间的侵占是最小的,而多连杆和双叉臂对于车辆空间侵占是要更大的。

  • 湖南省医保局2015年工作思路与安排 湖南省医疗保障局领导班子组成人员

    督促指导各统筹地区核实提高缴费基数,强化保险费足额征收。继续加强工伤认定参与,把好工伤入口关。认真核实、积极处理群众举报问题,始终保持高压态势。加强生育医疗服务管理,规范生育津贴发放。二是启动实施工伤保险信息系统改造升级,改进工伤职工异地就医联网结算,方便工伤职工救治。三是加强财务、业务数据清理,提高数据质量;通报全省“三险”基金运行分析,指导市州加强基金运行风险管控。

  • 民国最渣四大渣男(民国著名4大渣男)

    当时很多文人在接受自由恋爱的思想时,家中已经有了父母为之安排的妻子。郁达夫一生有过三位妻子,一位同居情人。郁达夫后来还是和王映霞离婚,1940年在新加坡认识了比他小20岁的播音员李莜英,两人很快就同居了。第二任妻子佐藤富子,是个日本女人,为了和郭沫若在一起,不仅改名为“郭安娜”,还和父母断绝了关系。1937年,郭沫若抛弃妻子回国,和女明星于立群同居,两人于2年后再重庆结婚。

  • 电脑怎么连打印机教程(教会你快速学会电脑如何连接打印机的安装使用方法)

    最近很多网友都在私信给小编,小编也无法一一回复,有些问题也无法简约介绍,所以只能在头条文章内与大家共享。

  • 爱吃鸡蛋的注意了这3种鸡蛋不能买(这些鸡蛋没你想的那么好)

    营养均衡的孩子没必要补这种元素;真正缺乏硒,靠富硒蛋补,根本起不了多大作用。这类蛋再好,也别给孩子吃那就是全生或半熟的蛋,比如溏心蛋。一般溏心蛋的加热时间短,不能完全杀死细菌,生蛋液根本没有处理细菌,对于抵抗力低、易感染的宝宝来说,非常容易被细菌感染。