java根据map的key按字典序排序

应用场景:
一般用于计算签名时

package data.demo.utils;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
	/**
	 *  根据map的key进行字典升序排序
	 * @param map
	 * @return map
	 */
	public static Map<String, Object> sortMapByKey(Map<String, Object>map) {
		Map<String, Object> treemap = new TreeMap<String, Object>(map);
		List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(treemap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
		return treemap;
	}

   /**
	* 将map转换成url参数
    * @param map
    * @return
    */
   public static String getUrlParamsByMap(Map<String, Object> map) {
       if (map == null) {
           return "";
       }
       StringBuffer sb = new StringBuffer();
       try {
       	for (Map.Entry<String, Object> entry : map.entrySet()) {
               sb.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
               sb.append("&");
           }
		} catch (Exception e) {
			e.printStackTrace();
		}
       String s = sb.toString();
       if (s.endsWith("&")) {
           s = StringUtils.substringBeforeLast(s, "&");
       }
       return s;
   }

你可能感兴趣的:(java)