按Key排序
使⽤TreeMap<K,V>,向其构造⽅法 TreeMap(Comparator<? super K> comparator) 传⼊我们⾃定义的⽐较器即可实现按键排序。
按Value排序
将待排序Map中的所有元素置于⼀个列表中,接着使⽤Collections的⼀个静态⽅法 sort(List list, Comparator<? super T> c) 来排序列表,同样是⽤⽐较器定义⽐较规则。排序后的列表中的元素再依次装⼊Map,为了肯定的保证Map中元素与排序后的List中的元素的顺序⼀致,使⽤了LinkedHashMap数据类型。 public static void main(String[] args){
Map<String, String> map =new TreeMap<String, String>();
map.put("KFC","kfc");
map.put("WNBA","wnba");
map.put("NBA","nba");
map.put("CBA","cba");
Map<String, String> resultMap =sortMapByKey(map);//按Key进⾏排序
Map<String, String> resultMap =sortMapByValue(map);//按Value排序
for(Map.Entry<String, String> entry : Set()){
System.out.Key()+" "+ Value());
}
}
/**
* 使⽤ Map按key进⾏排序
* @param map
* @return
*/
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 MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
class MapKeyComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2){
pareTo(str2);// str1>str2? -1:1 ; str1=str2,返回0
}
}
/**
* 使⽤ Map按value进⾏排序
* @param map
* @return
*/
public static Map<String, String>sortMapByValue(Map<String, String> oriMap){
if(oriMap == null || oriMap.isEmpty()){
return null;
}
Map<String, String> sortedMap =new LinkedHashMap<String, String>();
List<Map.Entry<String, String>> entryList =new ArrayList<Map.Entry<String, String>>( Set());
Collections.sort(entryList,new MapValueComparator());
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while(iter.hasNext()){
tmpEntry = ();
sortedMap.Key(), Value());
}
return sortedMap;
}
class MapValueComparator implements Comparator<Map.Entry<String, String>>{
@Override
public int compare(Entry<String, String> me1, Entry<String, String> me2){
Value().Value());
}
}
按Value排序还可以把value全部单独保存到List,再进⾏排序;根据排序好的列表,到对应的key,再装⼊Map中。
Collection<String> valueCollection = resultMap.values();
List resultList =new ArrayList<String>(valueCollection);