Java根据Map的key的ASCII码从⼩到⼤排序
1.主要有两种⽅式,第⼀种使⽤treemap,第⼆种使⽤sort⽅法对map的key进⾏排序重组⼀个新的map 。⼀般使⽤treemap import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Test3 {
public static void main(String[] args) {
// ⽅式⼀:TreeMap可以⾃动排序
TreeMap<String, Object> params = new TreeMap<String, Object>();
setData(params);
StringBuilder s1 = new StringBuilder();
for (String key : params.keySet()) {
s1.append(key).append("=").(key)).append("&");
}
s1.deleteCharAt(s1.length() - 1);
System.out.println(s1);
//⽅式⼆:使⽤HashMap,并使⽤Arrays.sort排序
HashMap<String, Object> params2 = new HashMap<String, Object>();
setData(params2);
String[] sortedKeys = params2.keySet().toArray(new String[]{});
用sort outArrays.sort(sortedKeys);// 排序请求参数
StringBuilder s2 = new StringBuilder();
for (String key : sortedKeys) {
s2.append(key).append("=").(key)).append("&");
}
s2.deleteCharAt(s2.length() - 1);
System.out.println(s2);
System.out.String().String()));
}
private static void setData(Map<String,Object> params){
params.put("Nonce", 11886);
params.put("Timestamp", 1465185768);
params.put("SecretId", "AKIDz8krbsJ5yKBZQpn74WFkmLPx3EXAMPLE");
params.put("Action", "DescribeInstances");
params.put("Version", "2017-03-12");
params.put("Region", "ap-guangzhou");
params.put("Limit", 20);
params.put("Offset", 0);
params.put("测试", "测试");
}
}
2.另外 fastjson如果使⽤1.2.31及以上版本,如果需要转成json时候可以直接在转json的时候排序
Map message = new HashMap();
message.put("channel_id","1000000xxxxx");
message.put("request_no", "1705105267714827140");
message.put("timestamp",new Date().getTime());
String sign = JSONString(message, SerializerFeature.MapSortField);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。