TreeSet集合元素排序

TreeSet集合元素排序

TreeSet集合存储自定义对象:

默认需要实现Comparator,也可以通过比较器来实现,请看如下:

 

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetSummarize {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		operateObject();
	}

	public static void operateObject(){
		TreeSet<Colleague> treeSet = new TreeSet<Colleague>(new cComparator());
		Colleague colleague1 = new Colleague("xiashengbing", 32, "engineer");
		Colleague colleague2 = new Colleague("lifenghong", 35, "manager");
		Colleague colleague3 = new Colleague("yangwei", 29, "designer");
		Colleague colleague4 = new Colleague("dongyuxing", 46, "outsourcing");
		Colleague colleague5 = new Colleague("qingshan", 38, "executive");
		treeSet.add(colleague1);
		treeSet.add(colleague2);
		treeSet.add(colleague3);
		treeSet.add(colleague4);
		treeSet.add(colleague5);
		printTreeSet(treeSet);
		
	}
	
	public static void printTreeSet(TreeSet<Colleague> treeSet){
		for (Iterator<Colleague> iterator = treeSet.iterator(); iterator.hasNext();) {
			Colleague prisoner = iterator.next();
			System.out.println(prisoner);
		}
	}
}


 

import java.util.Comparator;

import cn.itcast.list.Person;

class cComparator implements Comparator<Colleague>
{
	@Override
	public int compare(Colleague o1, Colleague o2) {
		// TODO Auto-generated method stub
		int num = o1.getPosition().compareTo(o2.getPosition());
		if(num == 0)
		{
			return o1.getName().compareTo(o2.getName());
		}
		return num;
	}
}

public class Colleague extends Person implements Comparable<Colleague>{

	private String position;
	public Colleague(String name, int age, String position) {	
		// TODO Auto-generated constructor stub
		super(name, age);
		this.setPosition(position);
	}
	
	@Override
	public int compareTo(Colleague o) {
		// TODO Auto-generated method stub
		int num = this.getName().compareTo(o.getName());
		if(num == 0)
		{
			return new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
		}
		return num;
	}
	
	public void setPosition(String position) {
		this.position = position;
	}
	public String getPosition() {
		return position;
	}
	public String toString(){
		return this.getName()+"..." + this.getAge() + "..." + this.position;
	}

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值