TreeSet按实体类字段排序

1.常规类型

TreeSet的自然排序是根据元素的大小进行升序排序,若想自己定制排序,比如降序,就可以使用Comparator接口。

@Test
	//自动排序
	public void treeSets() {
		Set<Integer> set = new TreeSet<>();
		set.add(2);
		set.add(5);
		set.add(25);
		set.add(15);
		set.add(10);
		System.out.println(set);

	}

输出:[2, 5, 10, 15, 25] 

 

 

2.实体类排序

上代码

 

public class Demo15 {
	public static void main(String[] args) {
		/**
		 * 实现定制排序,提供Comparator对象,负责排序逻辑
		 */
		Set<Man> mans = new TreeSet<>(new MyComparator());
		mans.add(new Man(11));
		mans.add(new Man(33));
		mans.add(new Man(22));
		mans.add(new Man(131));
		mans.add(new Man(110));
		System.out.println(mans);
	}
}

class Man {
	private Integer age;

	public Integer getAge() {
		return this.age;
	}

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

	public Man(Integer age) {
		super();
		this.age = age;
	}

	@Override
	public String toString() {
		return "Man[age:" + age + "]";
	}
}

class MyComparator implements Comparator<Man> {
	//顺序排序
	//如果需要降序排序,将返回值更改
	@Override
	public int compare(Man o1, Man o2) {
		if (o1.getAge() > o2.getAge()) {
			return 1;//降序:-1
		}
		if (o1.getAge() < o2.getAge()) {
			return -1;//降序:1
		}

		return 0;
	}

}

 输出:[Man[age:11], Man[age:22], Man[age:33], Man[age:110], Man[age:131]]

 

TreeSet的自然排序是根据元素的大小进行升序排序,若想自己定制排序,比如降序,就可以使用Comparator接口。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值