Initialize Map using Apache Commons Collections in Java

In this post, we will discuss various methods to initialize map using Apache Commons Collections in Java.


 

1. MapUtils.EMPTY_MAP

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

 

2. MapUtils.unmodifiableMap()

Apache Commons Collections MapUtils class provides 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 modify operation is performed on it.

 

3. MapUtils.putAll()

Apache Commons Collections MapUtils class also provides putAll(Map 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 sub-array 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 sub-array or entry matching used and an entry is invalid.
3. ClassCastException if the array contents is 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 existing elements can be changed (for instance, via the Map.put(Object,Object) method). But any change is made to the underlying map will be reflected back in the returned map. The map will throw an UnsupportedOperationException if any resize operation is performed on it.

Java

Download

 

5. Multimap

Multimap is a collection that maps keys to values, similar to Map, but in which 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

 
Related Posts:

1. Initialize Map in Java

2. Initialize Map using Guava Library in Java

 
References: MapUtils (Apache Commons Collections 3.2.2 API)

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz