Map排序类:
package MapSort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SortMap {
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>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
public static Map<String, String> sortMapByKey(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String key1, String key2) {
int intKey1 = 0, intKey2 = 0;
try {
intKey1 = getInt(key1);
intKey2 = getInt(key2);
} catch (Exception e) {
intKey1 = 0;
intKey2 = 0;
}
return intKey1 - intKey2;
}});
sortedMap.putAll(oriMap);
return sortedMap;
}
private static int getInt(String str) {
int i = 0;
try {
Pattern p = Pattern.compile("^\\d+");
Matcher m = p.matcher(str);
if (m.find()) {
i = Integer.valueOf(m.group());
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return i;
}
}
值的比较器类
package MapSort;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
public class MapValueComparator implements Comparator<Map.Entry<String, String>> {
@Override
public int compare(Entry<String, String> me1, Entry<String, String> me2) {
int value1=Integer.parseInt(me1.getValue());
int value2=Integer.parseInt(me2.getValue());
return value1-value2;
}
}
测试:
package MapSort;
import java.util.HashMap;
import java.util.Map;
public class MapSortTest {
public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
map.put("44", "1");
map.put("11", "4");
map.put("33", "3");
map.put("22", "2");
System.out.println(map);
System.out.println("----------\n按键排序:");
Map<String, String> map2=SortMap.sortMapByKey(map);
System.out.println(map2);
System.out.println("----------\n按值排序:");
Map<String, String> map3=SortMap.sortMapByValue(map);
System.out.println(map3);
}
}
测试结果:
{44=1, 11=4, 33=3, 22=2}
----------
按键排序:
{11=4, 22=2, 33=3, 44=1}
----------
按值排序:
{44=1, 22=2, 33=3, 11=4}