古老的榕树

Java Map 按 key 升序排序

发表 2017-03-18 23:48 阅读(4051)

最近开发微信和支付宝的服务端支付,涉及到字典的排序和 url 参数转换成字典的操作,整理了一个工具类:



import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class MapUtil {
	/**
     * 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;
	}

	/**
     * 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 >> (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;
	}

	/**
     * 将 Url Params String 转为 Map
     * 
     * @param param
     *            aa=11&bb=22&cc=33
     * @return map
     */
	public static Map < String,
	Object > urlParams2Map(String param) {
		Map < String,
		Object > map = new HashMap < String,
		Object > ();
		if ("".equals(param) || null == param) {
			return map;
		}
		String[] params = param.split("&");
		for (int i = 0; i < params.length; i++) {
			String[] p = params[i].split("=");
			if (p.length == 2) {
				map.put(p[0], p[1]);
			}
		}
		return map;
	}

	/**
     * 将 map 转为 Url Params String
     * 
     * @param map
     * @return aa=11&bb=22&cc=33
     */
	public static String map2UrlParams(Map < String, String > map, boolean isSort) {
		if (map == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		List < String > keys = new ArrayList < String > (map.keySet());
		if (isSort) {
			Collections.sort(keys);
		}
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = map.get(key).toString();
			sb.append(key + "=" + value);
			sb.append("&");
		}
		String s = sb.toString();
		if (s.endsWith("&")) {
			s = s.substring(0, s.lastIndexOf("&"));
		}
		return s;
	}
}

class MapKeyComparator implements Comparator < String > {
        @Override 
        public int compare(String str1, String str2) {
		return str1.compareTo(str2);
	}
}

class MapValueComparator implements Comparator < Map.Entry < String, String >> {
        @Override 
        public int compare(Entry < String, String > me1, Entry < String, String > me2) {
		return me1.getValue().compareTo(me2.getValue());
	}
}



另外按 map 的 key ascii 码升序排列,还有一个更简单的办法,如下面的语句:

SortedMap<String, String> smap = new TreeMap<String, String>(map);


注意 map 是现成无序的字典,依赖 SortedMap 和 TreeMap 转换就可以搞定了,很简单。

Donate

如果文章对您有帮助,请使用手机支付宝扫描二维码,捐赠X元,作者离不开读者的支持!