Converts the given array into a {@link java.util.Map}. Each element of the array * must be either a {@link java.util.Map.Entry} or an Array, containing at least two * elements, where the first element is used as key and the second as * value.
* *This method can be used to initialize:
** // Create a Map mapping colors. * Map colorMap = MapUtils.toMap(new String[][] {{ * {"RED", "#FF0000"}, * {"GREEN", "#00FF00"}, * {"BLUE", "#0000FF"}}); ** *
This method returns null
for a null
input array.
null
* @return a Map
that was created from the array
* @throws IllegalArgumentException if one element of this Array is
* itself an Array containing less then two elements
* @throws IllegalArgumentException if the array contains elements other
* than {@link java.util.Map.Entry} and an Array
*/
public static Map toMap(Object[] array) {
if (array == null) {
return null;
}
final Map map = new HashMap((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Object object = array[i];
if (object instanceof Map.Entry) {
Map.Entry entry = (Map.Entry) object;
map.put(entry.getKey(), entry.getValue());
} else if (object instanceof Object[]) {
Object[] entry = (Object[]) object;
if (entry.length < 2) {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', has a length less than 2");
}
map.put(entry[0], entry[1]);
} else {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', is neither of type Map.Entry nor an Array");
}
}
return map;
}
}