Friday, May 9, 2008

How to Store Multiple Values for Single Key in Java?

Please refer Apaches' Common configuration components.

It offers you :
MULTIVALUED MAP :Single Key Multiple Values
BIDIRECTIONAL MAP: Get the key, providing value

HOW TO READ MULTIPLE VALUES FOR SINGLE KEY FROM PROPERTY FILE IN JAVA?

By using Property class available in Java we can read the property file.
By using ResourceBundle also we can read property file.
But the limitations for both this class is property file should contain one to one mapping between key and value pair. It wont give an error while reading the file which has multiple values for single key(U always need this, right?i know...) but when u specify a key to read the value associated to this key from file, u will get the last value from the sequence of values for this key.
Ex. If you have specified something like this in your property file:
Key1 Value1
Key2 Value2
Key2 Value3
Key2 Value4
Key3 Value5

In this scenario when u'll try to read the value for the key key2 (properties.getValue("key2") it will return Value4 as it is last in the sequence of all values availeble for this key(key2).

Use Commons Configuration component provided by Apache to resolve this problem.
Commons Configuration component comes in package in couple of jar files.
It provides custom ways to manage you project configurations, property files, locale settings.

For the solution of our problem we need 3 jar files
--commons-configuration-1.5
--commons-collections-3.2.1
--commons-lang-2.4
--commons-logging-1.1.1
(Versions of these file may be changed when you are reading this stuff)

Put these files in your build path.
And code something like this:

Configuration config = new PropertiesConfiguration(PropertyFileName);
ArrayList arl = (ArrayList)config.getList(keyName);


Do I need to explain anything for above two lines?


>>Present tense is only tense, It takes care of past and future.We look at it correct persepective.