一般比较两个集合是否相等,基本都是使用循环去比较,下面介绍一个新的方式:前提是两个集合的顺序需要一样哈
package com.sport.sportactivityserver.common.utils;
import org.bouncycastle.util.encoders.Hex;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 获取对象的字符的hash值
* Created by zdj on 2021-03-23
*/
public class StringHashUtils {
public static String getHashValueByStr(String str) {
try {
// 创建获取一个MessageDigest对象,并且指定计算的类型: MD2|MD5|SHA-1|SHA-256|SHA-384|SHA-512
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.reset();
byte[] digest = messageDigest.digest(str.getBytes("utf-8"));
// hash数组为32位,否则就hash失败
if (digest.length != 32) {
System.out.println("计算hash值失败");
return null;
}
// 将计算得到的字节数组转为十六进制--并转换成字符串
return Hex.toHexString(digest);
} catch (UnsupportedEncodingException u) {
System.exit(-2);
} catch (NoSuchAlgorithmException n) {
System.exit(-3);
}
return null;
}
}
public static void main(String[] args) {
List<Map> a = Lists.newArrayList();
Map a1 = Maps.newHashMap();
a1.put("a", 11);
a1.put("a2", 23);
a1.put("a3", 41);
a.add(a1);
List<Map> s = Lists.newArrayList();
Map s1 = Maps.newHashMap();
s1.put("a", 11);
s1.put("a2", 23);
s1.put("a3", 41);
s.add(s1);
String a_hash = new StringHashUtils().getHashValueByStr(a.toString()); // 数据库的hash
String s_hash = new StringHashUtils().getHashValueByStr(s.toString()); // redis的hash
System.out.println(a_hash);
System.out.println(s_hash);
System.out.println(a_hash.equals(s_hash));
}