Can I have HashSets as keys in a HashMap? Suggest an alternative if not

Edit: Now correctly explained the problem.

I have a hashmap where I want to store the sets of words seen together (key) and the lines in which they were seen together (meaning). This is the structure I came across:

HashMap<HashSet<String>, HashSet<Integer>> hm= ...

for inputs:

  • mango, banana, apple

  • apple, banana

  • Peach walrus

  • walrus peach

Since I am reading this, line by line, I am making new temporary keys (hashes that are not yet inserted into the hashmap) from the combination of words in the line. Each temporary key is a hash of a subset of the words in a string. If a temporary key already exists in my hashmap, which I check for

if(hashmap.containsKey(hashset))

I just add a new line to the corresponding key value, if not, I make a new entry in the hash map and take care of it.

. hasmmap.

my hasmmap, , .

[, ] = [1,2]

[, ] = [3,4]

...

,

if(hashmap.containsKey(hashset))

. ? ?

+5
3

, . - , - , . javadoc Map:

: , . , , , - . , , . , , : equals hashCode .

, Collections.unmodifiableSet() ImmutableSet Guava.

+8

, HashSet HashMap, , HashSet.hashCode() , HashSet. , - , , HashSets (. )

MultiKeyMap MultiKey

+3

, , @Lukas ans @Matt.
, , , Hashset, equals hashCode , .

, .

+1

All Articles