Skip to content

Instantly share code, notes, and snippets.

@smat
Created July 11, 2011 18:45
Show Gist options
  • Save smat/1076498 to your computer and use it in GitHub Desktop.
Save smat/1076498 to your computer and use it in GitHub Desktop.
Java List to Map implementation
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapUtils {
public static <K, V> Map<K, V> listToMap(Class<K> keyClass, List<V> list, String valueToKeyFunctionName) {
HashMap<K, V> map = new HashMap<K, V>();
for (V value : list) {
try {
Method method = value.getClass().getMethod(valueToKeyFunctionName);
map.put((K) method.invoke(value), value);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return map;
}
}
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
public class MapUtilsTest {
@Test
public void testListToMap() {
List<String> strings = asList("test", "test2");
Map<String,String> hashCode = MapUtils.listToMap(String.class, strings, "hashCode");
System.out.println(hashCode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment