Store Multiple Values for a Key using Apache Collections

In 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *