Home » , » Store Multiple Values for a Key using Apache Collections

Store Multiple Values for a Key using Apache Collections

Written By Unknown on Senin, 09 Januari 2012 | 08.44

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");
map.put("mark","sophomore");
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: "+it.next()); // to print each value individually
   }
}



If you have any doubt, post it here.

Happy coding.
Share this article :

Posting Komentar

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger