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?
3 Answers
If you have a List of objects, you can do
List<String> list = ...
int hashCode = list.hashCode();
The hashCode uses the contents. There are lots of options for improving the hash code if you need but this is the simplest.
2 Comments
Try this:
int hashCode = Objects.hash(list.toArray());
6 Comments
toArray() returns an Object[], which is passed as the whole varargs.Arrays.asList( ... ).hashCode() for older versions of Java.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. A more robust solution, that relies only on the strings themselves could be to use 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.