简体   繁体   English

如何在Java中为Map创建唯一的ID?

[英]How do I create a unique id for Map in Java?

I am looking for a correct way to create unique ID for Map based on map's contents. 我正在寻找一种正确的方法来根据地图的内容为地图创建唯一的ID。 So,I expect IDs of 2 maps which contain the same data to be the same as well and have as small chance of collisions as possible. 因此,我希望包含相同数据的2个映射的ID也是相同的,并且尽可能少地发生冲突。

My current guess is using UUID, writing Map into Object and then building UUID from bytes. 我目前的猜测是使用UUID,将Map写入Object,然后从字节构建UUID。

 Map map;
 ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
 ObjectOutputStream out = new ObjectOutputStream(byteOut);

 out.writeObject(map);
 out.close();
 UUID.nameUUIDFromBytes(byteOut.toByteArray());

However, I wanted to ask if this is the optimal way and if not what else should I try? 但是,我想问这是否是最佳方式,如果不是,我还应该尝试什么?

To achieve this you can use any suitable for your needs (in terms of collisions, performance) hash function, for example, SHA-1: 要实现这一点,您可以使用任何适合您的需求(在冲突,性能方面)哈希函数,例如,SHA-1:

public class MainClas {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        Map<String, Integer> map = new HashMap<>();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);

        String mapString = map.entrySet().toString();
        System.out.println(mapString);

        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] hashBytes = digest.digest(mapString.getBytes());

        String hashString =  bytesToHex(hashBytes);

        System.out.println(hashString);
    }

    private static String bytesToHex(byte[] hashInBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) sb.append(String.format("%02x", b));
        return sb.toString();
    }
}

output: 输出:

[1=1, 2=2, 3=3]
1a1677fe956c66c776a100b32b0a2b20fdabb5f3

PS you can minimize collisions by using a composite hash from hashes produced from different algorithms (2 or 3). PS你可以通过使用从不同算法(2或3)产生的散列的复合散列来最小化冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM