I’m trying to write code that will create multiple HashSets using a for loop. I’m trying to store occurrences of unique words based on their length. For example, a word of length 4 would go in HashSet A, while a word of length 20 would go in HashSet B. Instead of creating 16 HashSets manually, is there a way for me to use a for loop (int i=4; i<21; i++)? Thank you!
I’m trying to write code that will create multiple HashSets using a for loop.
Share
Rather than having 16 different
HashSet‘s, you can have aMap<Integer, Set<String>>.So, while adding, you can just test whether a
keyis already there or not. If a key is there, just add the word to theSetfor that key, else add a new entry.So, here’re the steps you need to follow: –
length.Test if
Mapcontains keylength–Map#containsKey(Object)If
lengthkey is there, get theSetfor that key –Map#get(Object). And add thewordto thatSet.lengthkey is not there, create a newHashSet, add the current word in it. And add a new entry in yourMapwith the current length as key –Map#put(K, V)