I have a source HashMap in Java:
HashMap<String, Integer> keyWordFrequencies;
Storing keywords of various length. I want to traverse this HashMap and work out the lengths of the ngrams stored in the String part of the map which defines the text of each keyword.
With this data, I want to populate a target ArrayList of HashMaps:
ArrayList<HashMap<String, Integer>> keywordNgrams;
With the results, where the index of the ArrayList corresponds to the ngram size of a given keyword minus one, i.e. keywordNGrams(0) will receive the unigrams, keywordNGrams(1) will receive the bigrams and so on. But I'm not sure of the necessary syntax. Traversing the source HashMap is easy enough:
Set keyWordFrequenciesSet = keyWordFrequencies.entrySet();
Iterator keyWordFrequenciesIterator = keyWordFrequenciesSet.iterator();
while(keyWordFrequenciesIterator.hasNext()) {
Map.Entry m = (Map.Entry) keyWordFrequenciesIteratorIterator.next();
int ngramLength = String_Utils.getLengthOfNgram(m.getKey().toString());
Add element to keywordNgrams?
But adding the element to the target ArrayList of HashMap is confusing me. I have tried:
keywordNgrams.add(ngramLength, m);
And various alternatives but to no avail. m should be an element of a HashMap, not a HashMap in itself. Can anyone suggest where I am wrong?
Ideally, I would like to traverse the source HashMap keyWordFrequencies once, and the keywordNgrams ArrayList is initialised to the largest possible ngram size to start with.
keywordNgrams.size()will be? If so, then you're best off pre-populatingkeywordNgramsto that size; if not, then whenever you encounter a larger ngram than you've seen before, you'll need a loop to expandkeywordNgramsto the desired size.keywordNgrams.add(ngramLength, m);will not work becausemis aMap.Entryinstance, not an instance of aHashMap. Are you sure you want anArrayList<HashMap>and not anArrayList<Map.Entry>? With anArrayList<HashMap>, you will be creating a list of 5 elements, with each element being the exact same HashMap which I doubt is what you intend.