Monday, January 9, 2012

8:44 AM
n common programming we use maps to store key and value pair. They have one-to-one relationship.But, sometimes we need to use one-to-many relationship in order to store multiple values for a particular key.To achieve this we can use a hashmap to store a key and value will be a list.But,Here we'll discuss about Collections API given by Apache to do the trick.

First of all download the Collections API and keep it in your classpath. Now go through the sample code.

MultiMap map = new MultiValueMap();// map object with reference to the subclass MultiValueMap map.put("mark","purdue" ); // Adding of values into the map
map.put("mark", "Isec");
Set set = map.keySet(); // keyset method will fetch all the keys
for (Object o: set) { // advanced for loop to access all the keys
System.out.println("Values in "+o+" are: "+map.get(o)); // This will print the set of values for the key
List list = (List) map.get(o); // List to contain all the values for the key
Iterator it = list.iterator(); // Iterator to loop through all the values in the list
    while (it.hasNext())
      System.out.println("value: "; // to print each value individually

If you have any doubt, post it here.

Happy coding.


Javin Paul said...

Good one man. Google collections is another good open source library which you can use in conjunction with Java collections and Apache collections.

Top 15 Thread interview questions asked in Investment Banks