Tree map自定义排序

  1. 简单的
/**
 * 会自动排序
 */
public class TreeDemo4 {

	public static void main(String[] args) {
		Set<String> set = new TreeSet<String>();
		set.add("222");
		set.add("111");
		set.add("444");
		set.add("333");
		
		set.forEach(t->System.out.println(t));

	}

}
  1. 实现compable接口,重写compareto方法,需要修改类元素

/**
 * 自定义排序2 实现 Comparable 接口(修改元素类)
 */
public class TreeDemo {

	public static void main(String[] args) {
		Set<Stu> set = new TreeSet<Stu>();
		set.add(new Stu("222",2));
		set.add(new Stu("5",5));
		set.add(new Stu("111",1));
		set.add(new Stu("3",3));
		
		
		set.forEach(t->System.out.println(t));

	}

}

class Stu implements Comparable<Stu>{
	String name;
	Integer id;
	
	
	public Stu(String name, Integer id) {
		this.name = name;
		this.id = id;
	}


	@Override
	public int compareTo(Stu o) {
		return this.id - o.id;
	}


	@Override
	public String toString() {
		return "Stu [name=" + name + ", id=" + id + "]";
	}
	
	
	
	
}
  1. 自定义compator方法,不需要修改类元素
/**
 * 自定义排序3 使用 Comparator 比较器(不修改元素类)
 */
public class TreeDemo {

	public static void main(String[] args) {
		
		Comparator<Stu> comparator = new Comparator<Stu>() {
			
			@Override
			public int compare(Stu o1, Stu o2) {
				// TODO Auto-generated method stub
				return o1.id - o2.id;
			}
		};
		
		Set<Stu> set = new TreeSet<Stu>(comparator);
		set.add(new Stu("222",2));
		set.add(new Stu("5",5));
		set.add(new Stu("111",1));
		set.add(new Stu("3",3));
		
		
		set.forEach(t->System.out.println(t));

	}

}

class Stu{
	String name;
	Integer id;
	
	
	public Stu(String name, Integer id) {
		this.name = name;
		this.id = id;
	}


	@Override
	public String toString() {
		return "Stu [name=" + name + ", id=" + id + "]";
	}
	
	
	
	
}
  1. lamda表达式
/**
 * 自定义排序4 利用 Lambda表达式 或 方法引用 快速定义 Comparator:
 */
public class TreeDemo {

	public static void main(String[] args) {
		

		Set<Stu> set = new TreeSet<Stu>((p1,p2)->p1.id-p2.id);
		set.add(new Stu("222",2));
		set.add(new Stu("5",5));
		set.add(new Stu("111",1));
		set.add(new Stu("3",3));
		
		
		set.forEach(t->System.out.println(t));

	}

}

class Stu{
	String name;
	Integer id;
	
	
	public Stu(String name, Integer id) {
		this.name = name;
		this.id = id;
	}


	@Override
	public String toString() {
		return "Stu [name=" + name + ", id=" + id + "]";
	}
	
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值