今天刚好遇到一个需求,需要根据集合里边类的属性值进行排序,因此用到了Comparator接口,在此做下记录。
1.创建一个内部类,实现Comparator接口
class StudentComparator implements Comparator<DeviceGroupEntityRep> { /** 0代表升序,1代表降序 */ public StudentComparator(int orderby){ this.orderby = orderby; } private int orderby; @Override public int compare(DeviceGroupEntityRep d1, DeviceGroupEntityRep d2) { log.info(d2.getOrg().getOrgName().compareTo(d1.getOrg().getOrgName())+""); if ( 0 > d1.getOrg().getOrgName().compareTo(d2.getOrg().getOrgName())){ if (0 == this.orderby){ return -1; } else { return 1; } } else { if (0 == this.orderby){ return 1; } else { return -1; } } }
关于compareTo方法的返回值:调用方(即d1.getOrg().getOrgName())比参数排序靠前时,则返回大于0
关于compare方法的返回值:
负数和0时,排在左边的参数排在前面,假如要求升序时(即orderby=0),则若compareTo返回值大于0,返回-1
正数时,排在右边的参数排在前面,假如要求升序时(即orderby=1),则若compareTo返回值大于0,返回1
2.调用Collections.sort()方法,第一个参数为需要排序的集合,第二个参数创建实现Comparator接口的内部类
//升序 if ("0".equals(orderby.getOrgName()) || "0.0".equals(orderby.getOrgName())){ Collections.sort(deviceGroupEntityReps,new StudentComparator(0)); } //降序 else if ("1".equals(orderby.getOrgName())|| "1.0".equals(orderby.getOrgName())){ Collections.sort(deviceGroupEntityReps,new StudentComparator(1)); }