根据key排序
java.util包下的TreeMap可以满足此类需求,直接调用TreeMap的构造函数传入我们自己定义的比较器即可
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<String, String>(
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}});
sortMap.putAll(map);
return sortMap;
}
}
根据value排序
原理:将map中所有的entry元素放在list容器中,调用Collections里的静态方法sort(List list, Comparator< super T> c) 进行排序,重新compare方法定义排序规则。为了保证Map中元素与排序后的List中的元素的顺序一致,使用了LinkedHashMap。
public static Map<String, ExportExcelColumn> sortMapByValue(Map<String, ExportExcelColumn> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, ExportExcelColumn> sortedMap = new LinkedHashMap<String, ExportExcelColumn>();
List<Map.Entry<String, ExportExcelColumn>> entryList = new ArrayList<Map.Entry<String, ExportExcelColumn>>(oriMap.entrySet());
Collections.sort(entryList, new Comparator<Entry<String, ExportExcelColumn>>() {
@Override
public int compare(Entry<String, ExportExcelColumn> o1, Entry<String, ExportExcelColumn> o2) {
return o1.getValue().getColumnSortNum() - o2.getValue().getColumnSortNum();
}
});
Iterator<Map.Entry<String, ExportExcelColumn>> iter = entryList.iterator();
Entry<String, ExportExcelColumn> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
ExportExcelColum类
public class ExportExcelColumn {
private String columnName;
private Integer columnSortNum;
public ExportExcelColumn() {
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public Integer getColumnSortNum() {
return columnSortNum;
}
public void setColumnSortNum(Integer columnSortNum) {
this.columnSortNum = columnSortNum;
}
public ExportExcelColumn(String columnName, Integer columnSortNum) {
this.columnName = columnName;
this.columnSortNum = columnSortNum;
}
}