对集合中的对象进行排序


   有时候我们会对集合中的对象进行排序,而且这个排序是根据自身系统的业务来排序的。这个时候需要自己重写排序的具体业务。


在java中 我们可以实现Comparator接口,重写该接口的comapre方法即可


比如现在有以下需求, 对Student学生对象中的身高属性进行升序排序,如果身高一样就按照id降序排列。


实例如下:



package com.xiu.compare;
public class Student {
private Integer id;
// 学生年龄
private Integer age;
// 学生姓名
private String name;
// 学生的身高
private Integer height;

/**
* 重写toString()方法
*/


@Override
public String toString() {
// TODO Auto-generated method stub
return "ID:" + this.id + ",年龄" + age + ",姓名" + name + ",身高"
+ this.height;
}

public Student() {
}

public Student(Integer id, Integer age, String name, Integer height) {
this.id = id;
this.age = age;
this.name = name;
this.height = height;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getHeight() {
return height;
}

public void setHeight(Integer height) {
this.height = height;
}



比较器类

package com.xiu.compare;

import java.util.Comparator;

/**
 * 先判断身高,如果身高相等再判判断id
 * 
 * @author Administrator
 * 
 */
public class StudentComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {

if (s1.getHeight() > s2.getHeight()) {
return 1;

} else if (s1.getHeight() == s2.getHeight()) {

if (s1.getId() > s2.getId()) {

return 1;
} else if (s1.getId() == s2.getId()) {

return 0;
} else {

return -1;
}
} else {

return -1;
}

}

}



测试类

package com.xiu.compare;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestComparator {
public static void main(String[] args) {
List<Student>  users = new ArrayList<Student>();
Student  s1 = new Student(2,10,"zgh",187);
Student  s2 = new Student(1,10,"ss",175);
Student  s3 = new Student(4,20,"tt",180);
Student  s4 = new Student(3,30,"ss",180);
users.add(s1);
users.add(s2);
users.add(s3);
users.add(s4);

StudentComparator  sc = new StudentComparator();
Collections.sort(users,sc);

for (Student student : users) {

System.out.println(student);
}
}

}


运行结果

ID:1,年龄10,姓名ss,身高175
ID:4,年龄20,姓名tt,身高180
ID:3,年龄30,姓名ss,身高180
ID:2,年龄10,姓名zgh,身高187

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值