This post will discuss various methods to initialize a map using Apache Commons Collections in Java.

1. Using MapUtils.EMPTY_MAP

Apache Commons Collections provides Collections.EMPTY_MAP that returns an immutable empty map. It throws a UnsupportedOperationException if any modification operation is performed on it.

2. Using MapUtils.unmodifiableMap() method

Apache Commons Collections MapUtils class provides an unmodifiableMap() that returns an unmodifiable map backed by the given map.

 
It throws:

1. NullPointerException if the given map is null.
2. UnsupportedOperationException if any modification operation is performed on it.

3. Using MapUtils.putAll() method

Apache Commons Collections MapUtils class also provides putAll(Map<K,V> map, Object[] array) that puts all the keys and values from the specified array into the map.

If the first entry in the object array implements Map.Entry or KeyValue, then the key and value are added from that object. If the first entry in the object array is an object array itself, then it is assumed that index 0 in the subarray is the key and index 1 is the value. Otherwise, the array is treated as keys and values in alternate indices.

For example, to create a color map:

or:

or:

 
For different types of key-value pair:

 
It throws:

1. NullPointerException if the given map is null.
2. IllegalArgumentException if subarray or entry matching is used and an entry is invalid.
3. ClassCastException if the array contents are mixed.

4. Fixed-length empty Map

Apache Commons Collections MapUtils class has fixedSizeMap() method that returns a fixed-length map backed by the specified map.

Elements may not be added or removed from the returned map, but we can change existing elements (for instance, via the Map.put(Object, Object) method). But any change is made to the underlying map will be reflected in the returned map. The map will throw an UnsupportedOperationException if any resize operation is performed on it.

Download Code

5. Using Multimap

Multimap is a collection that maps keys to values, similar to a map, but each key may be associated with multiple values. We can use MultiMap to create a map that holds a collection of values against each key. There is only one implementation of Multimap available – MultiValueMap that uses an ArrayList by default; however, a class to instantiate or a factory returning a Collection instance may be specified.

Download Code

That’s all about initializing Map in Java using Apache Commons Collections.

 
Related Posts:

Initialize Map in Java

Initialize Map in Java using Guava Library

 
Reference: MapUtils (Apache Commons Collections 3.2.2 API)