Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training  




Share on Google+Share on Google+

1 Answer(s)      8 years ago
Posted in : Java Interview Questions
View Answers

August 25, 2009 at 10:50 AM

Hi Friend,

Try the following code:

import java.util.*;
import java.lang.reflect.*;

class Data{
private int key;
String value;
public Data(){}
public Data(int key, String value) {
this.key = key;
this.value = value;
public int getKey() {
return key;
public String getValue() {
return value;
public String toString(){
return key + " " + value;
public class ConvertArrayListToHashMap<K> {
public static String put(String str){
if(str != null && (str = str.trim()).length() > 0) {
str = str.substring(0, 1).toUpperCase() + str.substring(1);
return str;
public static String convertFieldToAccessor(String st) {
return "get" + put(st);
public <V> Map<K, V> convertToMap(List<V> list, String keyField) throws Exception {
String accessor = convertFieldToAccessor(keyField);
Map<K, V> map = new HashMap<K, V>();
for(V object : list) {
Method method = object.getClass().getDeclaredMethod(accessor);
K key = (K)method.invoke(object);
map.put(key, object);
return map;
public static void main(String[] args) throws Exception {
List<Data> list = new ArrayList<Data>();
list.add(new Data(1, "A"));
list.add(new Data(2, "B"));
list.add(new Data(3, "C"));
list.add(new Data(4, "D"));
Map<Long, Data> dimensionMap = new ConvertArrayListToHashMap<Long>().convertToMap(list, "key");

Hope that it will be helpful for you.


Related Tutorials/Questions & Answers:
COLLECTIONS12 - Java Interview Questions
COLLECTIONS12  HI i want source code of convert arraylist to hashmap i want key value fairs of each elment in arraylist.Convert Arrraykist to Hashmap.plz send me source code.  Hi Friend, Try the following code