Java SortedSet TreeSet按指定方式排序 不同方式排序

Java SortedSet TreeSet按指定方式排序 不同方式排序的列子

//实现Things类
class Things{
	public String name;
	public String id;
	String location;
	public String arrivetime;
	

	Things(String id, String name,String location,String arrivetime){
		this.id=id;
		this.name=name;
		this.location=location;
		this.arrivetime=arrivetime;
	}

	public String toString(){
		return"id:"+id+"\tname:"+name+"\tlocation:"+location+"\tarrivetime:"+arrivetime+"\n";
	}

}

//实现按ID进行比较
import java.util.Comparator;
public class SortById implements Comparator<Object>{

	@Override
	public int compare(Object o1, Object o2) {
		Things th1=(Things)o1;
		Things th2=(Things)o2;
		return th1.id.compareTo(th2.id);
	}
}

//实现按Time进行比较
import java.util.Comparator;
public class SortByTime implements Comparator<Object>{

	@Override
	public int compare(Object o1, Object o2) {
		Things th1=(Things)o1;
		Things th2=(Things)o2;
		return th1.arrivetime.compareTo(th2.arrivetime);
	}
}

//测试
import java.util.*;
class Demo5{
	public static void main(String args[]) {

	SortedSet<Things> ssa=new TreeSet<Things>(new SortById());	//创建一个按照Id排序的TreeSet实例a
	SortedSet<Things> ssb=new TreeSet<Things>(new SortByTime());	//创建一个按照Time排序的TreeSet实例b

	ssa.add(new Things("001","A","库1","2001-01-10"));	//添加的时候时间必须标准比如2011-11-1必须写成2011-11-01
	ssa.add(new Things("002","A","库1","2011-10-31"));
	ssa.add(new Things("003","B","库1","2011-10-03"));
	ssa.add(new Things("006","A","库2","2011-10-01"));
	ssa.add(new Things("007","B","库2","2011-10-30"));
	ssa.add(new Things("008","B","库2","2011-09-12"));
	ssa.add(new Things("004","B","库1","2011-09-02"));
	ssa.add(new Things("005","A","库2","2001-01-09"));

	
	int count1=0,count2=0,count3=0,count4=0;
	System.out.println("按ID排序:");
	Iterator<Things> it = ssa.iterator();
	while(it.hasNext()){
		Things c = it.next();
		ssb.add(c);	//从a中不断读取的时候就在b中添加
		System.out.print(c);
		if(c.name=="A" && c.location=="库1")
			 count1++;
			else 
			if(c.name=="A" && c.location=="库2")
			 count2++;	
			else
			if(c.name=="B" && c.location=="库1")
			 count3++;
			else
			if(c.name=="B" && c.location=="库2")
			 count4++;
	}
	
	
	System.out.println("按时间排序:");
	it = ssb.iterator();
	while(it.hasNext()){
		Things c = it.next();
		System.out.print(c);
	}

	System.out.println("A物料在库1的库存量为:"+count1);
	System.out.println("A物料在库2的库存量为:"+count2);
	System.out.println("B物料在库1的库存量为:"+count3);
	System.out.println("B物料在库2的库存量为:"+count4);
	}
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RobinTang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值