001package top.cenze.utils;
002
003import cn.hutool.core.util.ObjectUtil;
004
005import java.util.Iterator;
006import java.util.Map;
007import java.util.TreeMap;
008
009/**
010 * 排序工具
011 *
012 * @author chengze
013 * @date 2023-11-14 22:15
014 */
015public class SortUtil {
016
017    /**
018     * Map按Key的ASCII码排序
019     * @param maps
020     * @param ignoreNullValue 是否忽略空值key(默认为: true忽略)
021     * @return 排序后以&拼接的字符串
022     */
023    public static String sortMapByKey(Map maps, Boolean ignoreNullValue){
024        if (ObjectUtil.isNull(ignoreNullValue)) {
025            ignoreNullValue = true;
026        }
027
028        //把map的值存储到TreeMap中
029        TreeMap<Object, Object> treeMap = new TreeMap<Object, Object>();
030
031        for (Object map : maps.entrySet()){
032            Object value = ((Map.Entry) map).getValue();
033
034            // value为空时,忽略
035            if (ignoreNullValue && ObjectUtil.isNull(value)) {
036                continue;
037            }
038
039            // 对数据进行排序
040            treeMap.put(((Map.Entry) map).getKey(), value);
041        }
042
043        //遍历TreeMap并生成签名data
044        Iterator iter = treeMap.keySet().iterator();
045        StringBuffer sortData = new StringBuffer();
046        while (iter.hasNext()) {
047            String key = (String) iter.next();
048            String value = (String) treeMap.get(key);
049            sortData.append(key);
050            sortData.append("=");
051            sortData.append(value);
052            if (iter.hasNext()) {
053                sortData.append("&");
054            }
055        }
056
057        return String.valueOf(sortData);
058    }
059}