简体   繁体   English

Java-如何从字符串列表创建哈希ID

[英]Java- How to create hash id from a list of String

I have a list of String.我有一个字符串列表。 I want to generate one single hash code from all the strings of the list.我想从列表的所有字符串中生成一个哈希码。 How can I do that?我怎样才能做到这一点?

If you have a List of objects, you can do如果你有一个对象列表,你可以做

List<String> list = ...
int hashCode = list.hashCode();

The hashCode uses the contents. hashCode 使用内容。 There are lots of options for improving the hash code if you need but this is the simplest.如果需要,有很多改进哈希码的选项,但这是最简单的。

尝试这个:

int hashCode = Objects.hash(list.toArray());

You could just take the hashCode of the list, but that may be dodgy if you intend to have different implementations of List hold the same strings.您可以只使用列表的hashCode ,但如果您打算让List不同实现保存相同的字符串,这可能会很狡猾。 A more robust solution, that relies only on the strings themselves could be to use Arrays#hashCode :一个更强大的解决方案,只依赖于字符串本身可能是使用Arrays#hashCode

int hash = Arrays.hashCode(list.toArray());

Note, however, that this hash code depends on the order of the elements of the array, so if you don't care about the order of the strings in the list, you may want to sort this array so that the same strings produce the same hash code.但是请注意,此哈希码取决于数组元素的顺序,因此如果您不关心列表中字符串的顺序,您可能希望对该数组进行排序,以便相同的字符串产生相同的哈希码。

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

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