java set排序_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{

@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{

@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 ssa=new TreeSet(new SortById());//创建一个按照Id排序的TreeSet实例a

SortedSet ssb=new TreeSet(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 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);

}

}


版权声明:本文为weixin_42298062原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。