there is an open-source util library from Apache, where I found a method to convert an array into a map:
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;
}
Because I don't like warnings, I tried to add generics. But I don't know how to transfer the datatype from the input array to the output map.
Is it possible?
It is only possible if you create two separate methods: one that deals with Map.Entry elements, and another that deals with "array" elements (e.g. {"RED", "#FF0000"}). Here is the code:
public static <K, V> Map<K, V> toMap(Map.Entry<K, V>[] array) {
if (array == null) {
return null;
}
final Map<K, V> map = new HashMap<K, V>((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Map.Entry<K, V> entry = array[i];
map.put(entry.getKey(), entry.getValue());
}
return map;
}
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> toMap(Object[][] array) {
if (array == null) {
return null;
}
final Map<K, V> map = new HashMap<K, V>((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Object[] entry = array[i];
map.put((K) entry[0], (V) entry[1]);
}
return map;
}
Even though some some of the code is duplicated, it is arguably more elegant. I'm afraid there is no better solution for the second method; array can only be reified at runtime. Thus, "unchecked" casts have to be made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With