I'd like to calculate a hash of a set of strings in Java. Yes I can sort the strings and calculate the
MD5 hash iterative using digest.update
.
But I'd prefer to omit the sort and use something like combineUnordered
https://github.com/google/guava/wiki/HashingExplained
There is a lot of similar question asking the same such as Order-independant Hash Algorithm
but non of them provides a simple example showing how to calculate iterative an order independent hash in Java.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can calculate the MD5 hash of each string individually, and then, add them all to get a single hash. That will be order independent. Because addition operation is commutative.
Here is an example (assuming we have a method md5Hex(String str) that calculates md5 hash for a given string and returns the results in hexadecimal format):
Just XOR each hash and the order wont matter, plus the hash size will be fixed rather than grow with the size of the collection.
Hashcode using built in java string hashcode:
Hashcode using guava and MD5 like the question asked: