1. 程式人生 > >Map集合按照ASCII碼從小到大(字典序)排序--JAVA

Map集合按照ASCII碼從小到大(字典序)排序--JAVA

以下程式碼:將傳參按照ASCII 碼字典序排序,並將生成的字串進行MD5加密

	/**
	 * 生成簽名
	 * @param map
	 * @return
	 */
	public static String getSign(Map<String, String> map) {

		String result = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
			// 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序)
			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());
				}
			});
			
			// 構造簽名鍵值對的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, String> item : infoIds) {
				if (item.getKey() != null || item.getKey() != "") {
					String key = item.getKey();
					String val = item.getValue();
					if (!(val == "" || val == null)) {
						sb.append(key + ":" + val + ":");
					}
				}

			}
//			sb.append(PropertyManager.getProperty("SIGNKEY"));
			result = sb.toString();
			
			//進行MD5加密
			result = DigestUtils.md5Hex(result).toUpperCase();
		} catch (Exception e) {
			return null;
		}
		return result;
	}