1

I'm working on a nGrams, and I'm using a nested TreeMap kind of datastructure to store the ngrams. The template for Quadgrams looks like this.

public TreeMap<String, TreeMap<String, TreeMap<String, TreeMap<String, Integer>>>> ngramWordCounter;

The problem is arising when i'm trying to dump it to a file, basically i'm iterating over keySet of first map, and then into the keymap of the second and so on and so forth. As a result a lot of temporary objects are created and i'm getting GCOverlimitExceeded Error. The code snippet for iterating is as follows,

for(String key: ((Quadgram)quadgram).ngramWordCounter.keySet())
{
  for(String key1: ((Quadgram)quadgram).ngramWordCounter.get(key).keySet())
  {
    for(String key2: ((Quadgram)quadgram).ngramWordCounter.get(key).get(key1).keySet())
    {
        for(String key3:((Quadgram)quadgram).ngramWordCounter.get(key).get(key1).get(key2).keySet())
        {
            //Do something
        }
    }
  } 
}

Is there a better way to iterate over this list without creating temporary objects?

Rudra Murthy
  • 710
  • 2
  • 8
  • 20

1 Answers1

1

New objects won't be created. new references will be created.

Map returns reference to key in keyset. Use this reference to explore this concept or you can read java tutorials about this concept.

I prefer following way to iterate map is

for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
            String value = entry.getValue();
            // process key and value
}
Sagar Gandhi
  • 925
  • 6
  • 20
  • What happens to the references `String key` and `String value` after the loop terminates? These variables needs to be sweeped by GarbageCollector as Strings are indeed objects. [http://stackoverflow.com/questions/18406703/when-will-a-string-be-garbage-collected-in-java] – Rudra Murthy Mar 05 '14 at 06:04
  • yeah references will be removed not actual objects. If you check implementation, internally TreeMap stores Entry object itself. But all processing is inside the loop (guessing from given sample code) – Sagar Gandhi Mar 05 '14 at 08:49