Tag Archives: Apache

Apache Commons Collection – MultiValuedMap

The first time I needed a one-to-many map in Java, I reached for Map<String, List<String>> and wrote the same computeIfAbsent boilerplate I’d written a dozen times before. Apache Commons Collections’ MultiValuedMap exists specifically to kill that boilerplate — it’s a Map variant that lets a single key hold multiple values natively, without you manually managing the inner list. This post covers what it actually buys you over rolling your own, how it stacks up against Guava’s Multimap, and a realistic use case: grouping form-validation errors by field name.

Here’s the minimal example to see the API shape:

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"));
    }
}
Continue reading Apache Commons Collection – MultiValuedMap