Archive for hastable

Creating a map of maps in Java

Posted in Java with tags , , , on July 30, 2008 by vinaychilakamarri

At times I saw that some people get struck when it comes to creating a map of maps. It is not really a rocket science but needs a little sleight of hand. Here I will explain on how to create a map of maps in Java language. The same can be used for other languages. Also post in some of the other cool tricks if you may have any:

Here is the scenario… I have a text file in this format:

Gasoline Mexico $2.5

Gasoline USA $4.5

Gasoline Afghanistan $85

Beer Mexico $1.25

Beer USA $2.85

Beer Afghanistan $0.0

Now I want to query for ‘gasoline’ and get a map of all ‘country —> price’ listings. Similarly, I want to ask for beer and get a list of ‘country —> price’. This can be easily done by building a hashmap of hashmaps. As a visual guide, this is how the Datastructure will look like, after we’re done designing it:

My Approach:

Hashmap<String,Properties> gasBeerMap = new HashMap<String,Properties>();

//read the text file, get the inputstream

while(there are more lines in the textfile)

{

String[] tokens = tokenize the line;

Properties tmp = (Properties) gasBeerMap.get(tokens[0]);

if(tmp == null)

{

tmp = new Properties();
_gasBeerMap.put(tokens[0],tmp);

}

tmp.setProperty(tokens[1],tokens[2]);

}

This will check if the map for a specific entry is null. If it is, then it will insert a new map to that specific entry as it’s mapped value. As it can be observed, for the next iterations, the map will only get updated. This is one approach to the problem. Let me know if you have some cool approaches to this problem

Advertisements