list排序

如何实现自定义的排序规则:

1. list里面装的对象实现Comparable<T>接口,实现里面的public int compareTo(T another) 方法,返回为int  (>0正序)(<0逆序)(=0 不分先后),然后调用Collections.sort(List list);

2. 调用Collections.sort(List list, new Comparator<T>(T t1,T t2){} );


我在项目中用到的是第一种方法,结果忘记调用Collections.sort(List list)方法导致没排序。在此记录一下。


List<ServiceLevelEntity> entitys = new ArrayList<ServiceLevelEntity>();
			// Map<String, String> resultMap = new HashMap<String, String>();
			for (String key : map.keySet()) {
				ServiceLevelEntity entity = new ServiceLevelEntity();
				Map<String, Object> m = (Map) map.get(key);
				entity.setLevelInt((Integer) m.get("level"));
				entity.setLevelStr(String.valueOf(m.get("title")));
				entity.setDayUnitFee(Float.valueOf(m.get("day").toString()));
				entity.setNightUnitFee(Float.valueOf(m.get("night").toString()));
				// String s = "";
				// s += m.get("title").toString();
				// s += "(日班" + m.get("day") + "元  夜班" + m.get("night") + "元)";
				entitys.add(entity);
				Collections.sort(entitys);
			}


public class ServiceLevelEntity implements Serializable,Comparable<ServiceLevelEntity>{
	
	private static final long serialVersionUID = 1L;
	private float nightUnitFee;
	private float dayUnitFee;
	private String levelStr;
	private int levelInt;
	
	
	public int getLevelInt() {
		return levelInt;
	}
	public void setLevelInt(int levelInt) {
		this.levelInt = levelInt;
	}
	/* (non-Javadoc)
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(ServiceLevelEntity another) {
		// TODO Auto-generated method stub
		return this.getLevelInt()-another.getLevelInt();
	}
}


你可能感兴趣的:(list排序)