对集合中的对象进行排序

方法:实现Comparator接口并重写它的compare()方法,在方法内部制定排序规则。

我们有如下学生类,在不改变学生类源码的情况下,按照某种规则,对集合中存储的学生对象进行排序。

public class Student {
    private String id;
    private String name;
    private int chinese;
    private int math;
    private int english;
	public Student() {
		super();
		
	}
	public Student(String id, String name, int chinese, int math, int english) {
		super();
		this.id = id;
		this.name = name;
		this.chinese = chinese;
		this.math = math;
		this.english = english;
	}
 .....省略setter和getter方法
    }
}

1.利用TreeSet在添加元素前指定排序规则(这里是按语文成绩进行排序)

public class TreeSetSortTest {
     public static void main(String[] args) {
		TreeSet<Student> ts = new TreeSet<Student>( new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				return o1.getChinese()-o2.getChinese();
			}
		});
		ts.add(new Student("001", "张三", 90, 88, 76));
		ts.add(new Student("002", "李四", 98, 78, 90));
		ts.add(new Student("003", "jack", 78, 68, 55));
		
		for (Student student : ts) {
			System.out.println(student);
		}
	}
} 

打印结果:

Student [id=003, name=jack, chinese=78, math=68, english=55]
Student [id=001, name=张三, chinese=90, math=88, english=76]
Student [id=002, name=李四, chinese=98, math=78, english=90]


2.利用ArrayList集合存储学生对象,使用工具类Collections.sort ( List<T> list,Comparator<? super T> c)操作集合,对集合进行排序

public class ArrayListSortTest {
      public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("001", "张三", 90, 88, 76));
		list.add(new Student("002", "李四", 98, 78, 90));
		list.add(new Student("003", "jack", 78, 68, 55));
		
		Collections.sort(list, new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				return o1.getMath()-o2.getMath();
			}
		});
		
		for (Student student : list) {
			System.out.println(student);
		}
	}
}

打印结果:
Student [id=003, name=jack, chinese=78, math=68, english=55]
Student [id=002, name=李四, chinese=98, math=78, english=90]
Student [id=001, name=张三, chinese=90, math=88, english=76]


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值