Apache Commons Collection – MultiValuedMap

Apache Commons Collection is a library of useful data structures, collections, and algorithms in Java. MultiValuedMap is one of the data structures present in the Apache Commons Collection. MultiValuedMap is a Map that allows multiple values for a single key. It is a useful implementation of a one-to-many relationship. You can add multiple values to the same key, and the key-value pairs are stored in the order in which they are added.

Here’s an example Java code of using MultiValuedMap:

import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
public class MultiValuedMapDemo {
    public static void main(String[] args) {
        MultiValuedMap<String, String> multiValuedMap = new ArrayListValuedHashMap<>();
        multiValuedMap.put("Key1", "Value1");
        multiValuedMap.put("Key1", "Value2");
        multiValuedMap.put("Key2", "Value3");
        System.out.println(multiValuedMap.get("Key1"));
    }
}

In this example, we import the MultiValuedMap interface and its implementation ArrayListValuedHashMap from the Apache Commons Collection library. Then we create an instance of the MultiValuedMap with a key type of String and value type of String. We add multiple values to the same key “Key1” and one value to the key “Key2”. Finally, we print the values stored for the key “Key1”.

Here’s the output of this program:

[Value1, Value2]

As you can see, the MultiValuedMap returns a collection of values stored for the given key in the order in which they were added. In this case, the values for the key “Key1” are “Value1” and “Value2”.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.