List对象排序

1、对象继承Comparable接口,并重写compareTo方法

public class Human implements Comparable<Human> {
	private String name;
	private Integer age;
	public Human(String name ,Integer age){
		this.age = age;
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Human [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Human h) {
        //1排在当前的后面//-1排在当前的前面
		int big = -1,small = 1,eq =0;
		if(h == null||h.getAge()  ==null){
			return big;
		}else if(this.getAge()  ==null){
			return small;
		}else if(h.getAge() < this.getAge()){
			return big;
		}else if(h.getAge()>this.getAge()){
			return small;
		}
		return eq;
	}
}

二、使用Collections.sort(不去重进行排序);

		List<Human> list = new ArrayList<Human>();
		list.add(new Human("张三", 11));
		list.add(new Human("张四", 12));
		list.add(new Human("张三", 11));
		list.add(new Human("张七", 15));
		list.add(new Human("张八", 35));
		list.add(new Human("张九", 17));
		list.add(new Human("张五", 13));

		for (Human human : list) {
			System.out.println(human);
		}
		Collections.sort(list);
		System.out.println(1);
		for (Human human : list) {
			System.out.println(human);
		}

三、使用Tree进行排序(去重排序)

		List<Human> list = new ArrayList<Human>();
		list.add(new Human("张三", 11));
		list.add(new Human("张四", 12));
		list.add(new Human("张三", 11));
		list.add(new Human("张七", 15));
		list.add(new Human("张八", 35));
		list.add(new Human("张九", 17));
		list.add(new Human("张五", 13));

		for (Human human : list) {
			System.out.println(human);
		}
		
		System.out.println("set");
		Set<Human> set = new TreeSet<Human>();
		for (Human human : list) {
			set.add(human);
		}
		for (Human human : set) {
			System.out.println(human);
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值