Archive for Java

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

Maximizing a JFrame by default when it comes up

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

I’ve been playing around with JFreeCharts for a while.  The API’s perfect; the only problem is with the amount of data with labels that I wanted to show… it didn’t just fit in the dictionary of aesthetics. Best way to delude my users was to show the stuff maximized. I wanted to show a JFrame maximized by default. Here is what I did:

….

setExtendedState(getExtendedState()|MAXIMIZED_BOTH);

……

Here I am assuming that you wrote a class by extending from JFrame itself. If this is not the case, you need to use the instantiated object to call the ‘getExtendedState’ method. Also use JFrame to call ‘MAXIMIZED_BOTH’:

…..

JFrame fr = …

fr.setExtendedState(fr.getExtendedState()|JFrame.MAXIMIZED_BOTH);

….

Have fun 😉