Created
July 11, 2011 18:45
-
-
Save smat/1076498 to your computer and use it in GitHub Desktop.
Java List to Map implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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