Skip to content

Instantly share code, notes, and snippets.

@aembleton
Created July 26, 2011 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aembleton/1106478 to your computer and use it in GitHub Desktop.
Save aembleton/1106478 to your computer and use it in GitHub Desktop.
Converts a List into a Map where the key is set to the value returned by calling the getter for the specified keyProperty on each element of the List and the value is set to the object held in the List.
package net.blerg.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility for {@link Map}s
* @author arthur
*
* @param <Key> Key type
* @param <Value> Value type
*/
public class MapUtil<Key, Value> {
private static final Logger log = LoggerFactory.getLogger(MapUtil.class);
/**
* Converts a {@link List} into a {@link Map} where the key is set to the
* value returned by calling the getter for the specified keyProperty on
* each element of the List and the value is set to the object held in the
* List.
*
* @param list
* The list to copy into a map
* @param keyProperty
* Name of the property from which to read the value used to set
* the key
* @return A {@link HashMap} containing the values of the {@link List}. An
* empty map will be returned if the getter could not be found, and
* any elements where the getter returned an exception will also not
* be included.
*/
@SuppressWarnings("unchecked")
public Map<Key, Value> fromList(List<Value> list, String keyProperty) {
Map<Key, Value> map = new HashMap<Key, Value>();
if (list == null || list.size() < 1) {
return map;
}
Value valueObj = list.get(0);
Class<?> clazz = valueObj.getClass();
Method keyGetter;
try {
keyGetter = clazz.getMethod("get" + capitiliseFirstChar(keyProperty));
} catch (SecurityException e) {
log.error("Got a security exception when trying to get " + keyProperty);
return map;
} catch (NoSuchMethodException e) {
log.error("There is no method called " + keyProperty);
return map;
}
for (Value item : list) {
Key key;
try {
key = (Key) keyGetter.invoke(item);
map.put(key, item);
} catch (IllegalArgumentException e) {
log.error("The getter requires arguments, this is not currently supported.", e);
} catch (IllegalAccessException e) {
log.error("This getter is inaccessible.", e);
} catch (InvocationTargetException e) {
log.error("The getter threw an exception.", e);
}
}
return map;
}
private String capitiliseFirstChar(String string) {
return String.format("%s%s", Character.toUpperCase(string.charAt(0)), string.substring(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment