1

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?

1
  • 2
    add them to a list and get list.hashCode() Commented Oct 27, 2018 at 14:17

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Does this apply to every Collection children, or just List?
@JoãoMatos All collections generate a hashCode based on the contents of the elements, keys/values. Note: if you change any element, key or value and this is in a HashSet or a key of a Map this can corrupt that collection.
2

Try this:

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

6 Comments

I would make sure this doesn't hash the array instead of the contents.
@peter it doesn’t, because toArray() returns an Object[], which is passed as the whole varargs.
@peter but I like your answer better :)
@peter yeah, re DV, although clunky, this is the general answer to hashing a bunch o’ stuff
Or Arrays.asList( ... ).hashCode() for older versions of Java.
|
1

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.

1 Comment

This is better if you don't trust how the List has been implemented, or I would avoid using a List implementation I don't trust.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.