forked from kidgrow-microservices-platform

zhaoxiaohao
2020-12-28 861200b968f21a748aa322635f55e48e79dafb1e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.kidgrow.common.utils;
 
import java.net.URLEncoder;
import java.util.*;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: 排序工具类<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/4 13:58 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
public class SortUtils {
 
    public static Map<String, String> orderParam(Map<String, String> map) {
        HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
 
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
 
        for (int i = 0; i < infoIds.size(); i++) {
            Map.Entry<String, String> item = infoIds.get(i);
            tempMap.put(item.getKey(), item.getValue());
        }
        return tempMap;
    }
 
    /**
     * @param param 参数
     * @return
     */
    public static String formatUrlParam(Map<String, String> param) {
        String params = "";
        Map<String, String> map = param;
 
        try {
            List<Map.Entry<String, String>> itmes = new ArrayList<Map.Entry<String, String>>(map.entrySet());
 
            //对所有传入的参数按照字段名从小到大排序
            //Collections.sort(items); 默认正序
            //可通过实现Comparator接口的compare方法来完成自定义排序
            Collections.sort(itmes, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    // TODO Auto-generated method stub
                    return (o1.getKey().toString().compareTo(o2.getKey()));
                }
            });
 
            //构造URL 键值对的形式
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> item : itmes) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    if(!"sign".equals(key)) {
                        String val = item.getValue();
                        val = URLEncoder.encode(val, "UTF-8");
                        sb.append(val);
                    }
                }
            }
            params = sb.toString();
        } catch (Exception e) {
            return "";
        }
        return params;
    }
}