List集合的两种排序方式

前几天听同事给我分享List的两种排序方式,于是就写了一个demo,分享给大家。

1、利用java.util.Collections.sort(List<Object> list, Comparator<? super Object> c)自带方法进行排序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {

	private String name;
	private int score;

	public Test(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}

	public String getName() {
		return name;
	}

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

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public static void main(String[] args) {
		List<Test> list = new ArrayList<Test>();
		list.add(new Test("张三", 100));
		list.add(new Test("李四", 98));
		list.add(new Test("王五", 99));
		list.add(new Test("赵六", 98));
		list.add(new Test("马七", 89));

		Collections.sort(list, new Comparator<Test>() {
			@Override
			public int compare(Test o1, Test o2) {
				int i = o1.getScore() - o2.getScore();
				return i;
			}
		});
		for (Test tes : list) {
			System.out.println("姓名:" + tes.getName() + ",分数:" + tes.getScore());
		}
	}

}

当用o1-o2时,是正序排列,当o2-o1时,是倒序排列。

运行结果:

姓名:马七,分数:89
姓名:李四,分数:98
姓名:赵六,分数:98
姓名:王五,分数:99
姓名:张三,分数:100

2、实现Comparable<Test>接口

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test implements Comparable<Test>{

	private String name;
	private int score;

	public Test(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}

	public String getName() {
		return name;
	}

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

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	@Override
	public int compareTo(Test o) {
		int i =  this.score - o.score;//正序排列
		//int i =  o.score - this.score;//倒序排列
		return i;
	}
	
	public static void main(String[] args) {
		List<Test> list = new ArrayList<Test>();
		list.add(new Test("张三", 100));
		list.add(new Test("李四", 98));
		list.add(new Test("王五", 99));
		list.add(new Test("赵六", 98));
		list.add(new Test("马七", 89));
		Collections.sort(list);
		for (Test tes : list) {
			System.out.println("姓名:" + tes.getName() + ",分数:" + tes.getScore());
		}
	}

}

运行结果:

姓名:马七,分数:89
姓名:李四,分数:98
姓名:赵六,分数:98
姓名:王五,分数:99
姓名:张三,分数:100

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值